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
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.
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.
Simply put, :: is for class-level properties, and -> is for object-level properties.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With