What's the difference between self::CONSTANT_NAME
and static::CONSTANT_NAME
?
Is calling constant via static::
only 5.3 feature?
A class constant is declared inside a class with the const keyword. Class constants are case-sensitive. However, it is recommended to name the constants in all uppercase letters.
Constants that are specific to a class should go in that class's interface.
Class constants are useful when you need to declare some constant data (which does not change) within a class. There are two ways to access class constant: Outside the Class: The class constant is accessed by using the class name followed by the scope resolution operator (::) followed by the constant name.
When you use static::NAME it's a feature called late static binding (or LSB). More information about this feature is at the php.net documentation page of LSB: http://nl2.php.net/manual/en/language.oop5.late-static-bindings.php
An example is this use case:
<?php
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
self::who();
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test();
?>
This outputs A, which is not always desirable. Now replacing self
with static
creates this:
<?php
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
static::who(); // Here comes Late Static Bindings
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test();
?>
And, as you might expect, it ouputs "B"
The difference is pretty much what late static bindings are all about.
Short explanation:
self::
will refer to the class type inside which the code using self:: is written.
static::
will refer to the class type of the actual object that on which the code using static:: is being executed.
This means that there's only a difference if we are talking about classes in the same inheritance hierarchy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With