Difference between self::$bar and static::$bar in PHP
self keyword: It is a PHP keyword that represents the current class and used to access static class variables or static variables because these members belong to a class rather than the object of that class.
You can see for both the cases, the value of $bar is printed of demo class, even though for the second call we are trying the get the value of $bar for the child class. This happens because of ‘self’ keyword. Self only refers to the compile-time version of $bar or in simpler terms refers to the version of the class it resides in. In fact, it is considered to be a limitation of ‘self’ but it can be fixed by using ‘static’ keyword.
Static keyword: This PHP keyword helps the concept of “late static binding in PHP” to come in the picture. It is used to access the static function desired by the extended class at runtime.
the ‘static’ keyword covers the limitation held by the ‘self’ keyword by enforcing the concept of late static binding. In this scenario, static asks the compiler to print the version of the function for the class that asked for it. All of this happens at runtime, therefore late static binding is a way of showing polymorphism at run-time in PHP.
self Vs static: The most basic difference between them is that self points to the version of the property of the class in which it is declared but in case of static, the property undergoes a redeclaration at runtime.
Please Login to comment...