What's the difference between new self()
and new static()
in PHP? Are they the same?
No, they are not the same. In PHP, self
refers to the class in which the new
keyword is actually written, while static
refers to the class in the hierarchy where the method has been called. Consider the following example:
class Class_A {
public static function get_self() {
return new self();
}
public static function get_static() {
return new static();
}
}
class Class_B extends Class_A {}
echo get_class(Class_B::get_self()); // Output: Class_A
echo get_class(Class_B::get_static()); // Output: Class_B
echo get_class(Class_A::get_self()); // Output: Class_A
echo get_class(Class_A::get_static()); // Output: Class_A
In the example above, Class_B::get_self()
returns an instance of Class_A
, as self
always refers to the class in which the method is defined (Class_A
in this case). However, Class_B::get_static()
returns an instance of Class_B
, as static
refers to the class from which the method is called (Class_B
in this case). The last two lines demonstrate that the same behavior applies when calling the methods from the base class Class_A
.
By using self
, you can ensure that the same class is instantiated, regardless of the context in which the method is called. On the other hand, static
allows for late static binding, enabling the appropriate class to be instantiated based on the runtime context.