Class Constant Visibility
In PHP 7.1, the concept of public
,
protected
, and private
visibility of
properties and methods has been expanded to class constants. This
change allows for applying the information hiding principle also to
constants. It is now possible to hide implementation details such as
bitmasks and magic numbers from the user of a class.
The class in the example below declares a private constant named
FOO
and uses its value as the default for a constructor
parameter:
class C
{
private const FOO = 'bar';
public function __construct(string $parameter = self::FOO)
{
var_dump($parameter);
}
}
$o = new C;
Executing the code shown above will print the output shown below:
string(3) "bar"
Just like for properties and methods, it is a best practice that a class constant should be declared private unless there is a good reason for it to be protected or public.