Open In App

Difference between self::$bar and static::$bar in PHP

Last Updated : 03 Jun, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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:




<?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();
  
?>


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:




<?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();
   
?>


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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads