I was under the impression that const prevents the variable from being redefined!
const
prevents the value to be modified.
It is not possible to define two different objects that has the same name using define()
. It is also not possible to define two different objects that has the same name using const
. A const
class member is always accessed using its full name (class name + ::
+ constant name).
The name of the STEALTH
constant defined by the Person
class is Person::STEALTH
. The Ninja
class declares the constant Ninja::STEALTH
.
They are different objects.
const
(and static
) class properties are not inherited the same way instance properties are. If a const
property defined by the base class is not masked by another object with the same name defined by the child class, the base class const
property is copied in the child class and can be accessed using the child class name.
For example:
class Person {
const STEALTH = "MINIMUM";
}
class Citizen extends Person {
}
class Ninja extends Person {
const STEALTH = "MAXIMUM";
}
echo Person::STEALTH; // prints out 'MINIMUM'
echo Citizen::STEALTH; // prints out 'MINIMUM'; same as Person::STEALTH
echo Ninja::STEALTH; // prints out 'MAXIMUM'
Because class Citizen
extends class Person
and it doesn't define its own STEALTH
constant, Citizen::STEALTH
is a copy of Person::STEALTH
1.
Class constants are global objects with fancy names (and class visibility modifiers since PHP 7.0).