PHP Tutorial Tutorials - PHP OOP Class Constants

PHP OOP Class Constants

Class Constants are constants that are declared within classes.
They are allocated once per class, and not for each class instance.

The value is unchangeable, MUST be a constant expression, not (for example) a variable, a property, or a function call.

The default visibility of class constants is public.

Defining Class Constant

Use the keyword const to declare a class constant.

<?php
class MyClass
{
    const SITE = 'lautturi.com';
}
?>

Accessing Class Constants

There are two ways to access class constants:

  1. Use the keyword self and Scope Resolution Operator (::) to access Class Constants in the class.
function showConstant() {
    echo  self::SITE . "\n";
}
  1. Use the ClassName and Scope Resolution Operator (::) to access Class Constants outside the class.
echo  MyClass::SITE . "\n";

More About Class Constants

As of PHP 7.1.0, visibility modifiers are allowed for class constants.

<?php
class MyClass {
    // As of PHP 7.1.0
    private const ID = '19939';
    public const SITE = 'lautturi.com';
}
echo MyClass::SITE, PHP_EOL;
echo MyClass::ID, PHP_EOL; // Fatal error: Uncaught Error: Cannot access private const MyClass::ID
?>

As of PHP 5.3.0, You can initialize constants with Heredoc and Nowdoc syntax

<?php
class foo {
    // As of PHP 5.3.0
    const HOSTID = <<<'EOT'
LAU099
EOT;
    // As of PHP 5.3.0
    const SITE = <<<EOT
'lautturi.com'
EOT;
}
?> 

The special ::class constant is available as of PHP 5.5.0

<?php
namespace Lautturi {
    class MyClass {
    }

    echo MyClass::class; // Lautturi\MyClass
}
?> 

If you got a error message: Fatal error: No code may exist outside of namespace {} , check out if there some whitespace outside the {}.

Date:2019-10-09 01:10:07 From:www.Lautturi.com author:Lautturi