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.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Declaring parent class
class demo {
  
    public static $bar = 10;
  
    public static function func() {
        echo self::$bar . "\n";
    }
}
  
// Declaring child class
class Child extends demo {
    public static $bar = 20;
  
}
  
// Calling for demo's 
// version of func()
demo::func();
  
// Calling for child's 
// version of func()
Child::func();
  
?>

chevron_right


Output:

10
10

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.



Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
   
// Declaring parent class
class demo {
   
    public static $bar = 10;
   
    public static function func() {
                   
        // Static in place of self
        echo static::$bar."\n";
    }
}
   
// Declaring child class
class Child extends demo {
    public static $bar = 20;
}
   
// Calling for demo's version of func()
demo::func();
   
// Calling for child's version of func()
Child::func();
   
?>

chevron_right


Output:

10
20

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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.