In PHP, self::
, static::
, and parent::
are used to refer to different contexts in Object-Oriented Programming (OOP). Here's a detailed explanation of each, along with examples:
1. self::
self::
is used to access static properties and methods from within the same class. It refers to the class in which it is used, and does not account for inheritance. Therefore, it is a static reference to the class where the method or property was defined.
Example:
phpclass 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(); // Outputs: A
In this example, self::who()
in class A
refers to class A
's who
method, so the output is A
.
2. static::
static::
is similar to self::
, but it is late static bound. This means that it refers to the class that was called at runtime, rather than the class where the method was defined. It allows methods in parent classes to call methods that might be overridden in child classes.
Example:
phpclass A {public static function who() {echo __CLASS__;}public static function test() {static::who();}}class B extends A {public static function who() {echo __CLASS__;}}B::test(); // Outputs: B
In this example, static::who()
in class A
refers to class B
's who
method because test
was called on class B
, so the output is B
.
3. parent::
parent::
is used to refer to the parent class from within a child class. It allows a child class to call a method or access a property that is defined in its parent class.
Example:
phpclass A {public static function who() {echo __CLASS__;}public static function test() {self::who();}}class B extends A {public static function who() {echo __CLASS__;}public static function test() {parent::test(); // Calls A::test()}}B::test(); // Outputs: A
In this example, parent::test()
in class B
calls the test
method from class A
, which uses self::who()
, resulting in the output A
.
Summary
self::
: Refers to the class in which it is used. It does not consider inheritance and is resolved at compile-time.static::
: Refers to the class that was called at runtime, allowing for late static binding. This means it can be used to call methods that may be overridden in subclasses.parent::
: Refers to the parent class of the class in which it is used. It is used to call methods or access properties from the parent class.
Understanding these differences is crucial for correctly implementing inheritance and polymorphism in PHP OOP.
No comments:
Post a Comment