Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: self:: vs parent:: with extends

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

like image 297
djkprojects Avatar asked Jan 02 '14 16:01

djkprojects


People also ask

What is self :: in PHP?

self is used to access static or class variables or methods and this is used to access non-static or object variables or methods. So use self when there is a need to access something which belongs to a class and use $this when there is a need to access a property belonging to the object of the class.

What is parent :: PHP?

parent:: is the special name for parent class which when used in a member function.To use the parent to call the parent class constructor to initialize the parent class so that the object inherits the class assignment to give a name. NOTE: PHP does not accept parent as the name of a function.

What is :: VS --> in PHP?

Simply put, :: is for class-level properties, and -> is for object-level properties.

Can child classes override properties of their parents?

A child class can override any public parent's method that is not defined with the final modifier. Also, classes with final modifier cannot be extended.


1 Answers

                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.

like image 132
Mark Baker Avatar answered Oct 03 '22 23:10

Mark Baker