new self() vs new static() in PHP

What’s the difference between new self() and new static() in PHP? Or is it the same?

It is not the same. self refers the class in which the new keyword is actually written. static refers to the class in the hierarchy, where the method has been called. Look at 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());   // 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

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top