This post covers the Class Constants section of the OOP chapter when studying for the Zend PHP 7 Certification.
Class constants are constant values on a per-class basis that remain the same and are unchangeable.
Constants differ from normal variables in that you don’t use the $
symbol to declare or use them.
They are also publicly visible and cannot be made protected or private. A simple class constant declaration looks like the following:
<?php
class MyClass
{
const MYCONST = 'Some constant';
}
$class = new MyClass();
echo $class::MYCONST; // Outputs: Some constant
Constants are usually defined in uppercase and similar to variables they cannot start with a number. PHP 5.5 does not allow you to define an array constants. This is supported as of PHP 5.6, as PHP have made it possible to provide a scalar expression involving numeric and string literals.
<?php
class MyClass
{
const MYCONST = array("apples", "bananas");
const SEC_PER_DAY = 60 * 60 * 24;
}
$class = new MyClass();
print_r($class::MYCONST);
// PHP 5.5 output: Fatal error
// PHP 5.6+ output: Array ( [0] => apples [1] => bananas )
You can use the self
keyword when referencing a constant within a class method.
class MyClass
{
const CONSTANT = 'constant value';
function showConstant() {
echo self::CONSTANT . "\n";
}
}
$class = new MyClass();
$class->showConstant(); // Outputs: constant value
As of PHP 5.3, you can use HEREDOC and NOWDOC syntax to assist defining constants.
<?php
class foo {
const BAR = <<<'EOT'
bar
EOT;
const BAZ = <<<EOT
baz
EOT;
}
$class = new foo();
echo $class::BAR . "\n";
echo $class::BAZ;
// Outputs:
bar
baz
As of PHP 7.1.0 visibility modifiers are allowed for class constants.
<?php
class Foo {
public const BAR = 'bar';
private const BAZ = 'baz';
}
echo Foo::BAR, PHP_EOL;
echo Foo::BAZ, PHP_EOL;
// Outputs:
bar
Fatal error: Uncaught Error: Cannot access private const Foo::BAZ in …
View the other sections:
Note: This article is based on PHP version 7.1.0.