Open In App

New self vs. new static in PHP

New self: The self is keyword in PHP. It refers to the same class in which the new keyword is actually written. It refers to the class members, but not for any particular object. This is because the static members(variables or functions) are class members shared by all the objects of the class. The function called self::theFunction() behaves like “I will execute in the context of the class whom I physically belong to.”(Assuming the inheritance scenario).

New static: The static is a keyword in PHP. Static in PHP 5.3’s late static bindings, refers to whatever class in the hierarchy you called the method on. The most common usage of static is for defining static methods. Such methods are part of a class, just like any method, though they may be used even without any such instantiated object. The function called static::theFunction() behaves like “I will execute in the context of the class, which has been actually called by the outside world”.

PHP new self vs new static: Now that we changed the code in our example to use static instead of self, you can see the difference is that self references the current class, whereas the static keyword allows the function to bind to the calling class at runtime. The difference between self and static keywords is fairly easy to understand with an example.




<?php
class g {
      
    /* The new self */
    public static function get_self() {
    return new self();
    }
   
    /* The new static */
    public static function get_static() {
    return new static();
    }
}
   
class f extends g {}
   
echo get_class(f::get_self()); // g
echo get_class(f::get_static()); // f
echo get_class(g::get_self()); // g
?>

Output: In this example of code, f inherits both methods from g. The self invocation is bound to A because it is defined in g’s implementation of the method, whereas static is bound to the called class.

gfg

Article Tags :