PHP: self:: vs parent:: with extends

djkprojects picture djkprojects · Jan 2, 2014 · Viewed 16.2k times · Source

I'm wondering what is the difference between using self:: and parent:: when a static child class is extending static parent class e.g.

class Parent {

    public static function foo() {
       echo 'foo';
    }
}

class Child extends Parent {

    public static function func() {
       self::foo();
    }

    public static function func2() {
       parent::foo();
    }
}

Is there any difference between func() and func2() and if so then what is it ?

Thank you

Regards

Answer

Mark Baker picture Mark Baker · Jan 2, 2014
                Child has foo()     Parent has foo()
self::foo()        YES                   YES               Child foo() is executed
parent::foo()      YES                   YES               Parent foo() is executed
self::foo()        YES                   NO                Child foo() is executed
parent::foo()      YES                   NO                ERROR
self::foo()        NO                    YES               Parent foo() is executed
parent::foo()      NO                    YES               Parent foo() is executed
self::foo()        NO                    NO                ERROR
parent::foo()      NO                    NO                ERROR

If you are looking for the correct cases for their use. parent allows access to the inherited class, whereas self is a reference to the class the method running (static or otherwise) belongs to.

A popular use of the self keyword is when using the Singleton pattern in PHP, self doesn't honour child classes, whereas static does New self vs. new static

parent provides the ability to access the inherited class methods, often useful if you need to retain some default functionality.