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.
Use the keyword const to declare a class constant.
<?php
class MyClass
{
const SITE = 'lautturi.com';
}
?>
There are two ways to access class constants:
self and Scope Resolution Operator (::) to access Class Constants in the class.function showConstant() {
echo self::SITE . "\n";
}
::) to access Class Constants outside the class.echo MyClass::SITE . "\n";
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 {}.