What is the difference between new self()
and new static()
in PHP? Or are they the same?
They are not the same. self
refers to the class in which the new
keyword is written. On the other hand, static
refers to the class in the hierarchy in which the method is called. The following example illustrates this:
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()); // A
echo get_class(Class_B::get_static()); // B
echo get_class(Class_A::get_self()); // A
echo get_class(Class_A::get_static()); // A
In this example, get_self()
returns an instance of Class_A
because self
always refers to the class in which it is written, regardless of the calling class. On the other hand, get_static()
returns an instance of Class_B
when called from Class_B
, and an instance of Class_A
when called from Class_A
. This is because static
refers to the class in the hierarchy in which the method is called, allowing for late static binding.