Overriding/Static function call with static Keyword in PHP
In this blog, we will learn how we can call overridden static functions from the base class If that function is overridden by the derived class.
Lets understand it with an example of problem and solution code –
What’s The Problem ?
Suppose you create two static methods in a class BaseClass.
You have called the first static method getStaticText() from the second static method getStaticResult().
Now a child class DerivedClass extends the BaseClass and override the static method getStaticText().
See the below piece of code to understand it properly –
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?php Class BaseClass { // Static functions public static function getStaticText() { return 'Called from BaseClass'; } public static function getStaticResult() { // we can alternatively use BaseClass::getStaticText(); return self::getStaticText(); } } Class DerivedClass extends BaseClass { public static function getStaticText() { return 'Called from DerivedClass'; } } var_dump(DerivedClass::getStaticResult()); ?> |
Now if you call getStaticResult() from DerivedClass –
then the result of var_dump(DerivedClass::getStaticResult()) will be :
“Called from BaseClass“.
The getStaticText() function called from BaseClass as it is called with self keyword.
Case :
You have overrided the getStaticText() method in the DerivedClass.
Also you have called the method from DerivedClass – var_dump(DerivedClass::getStaticResult());
Here Let’s suppose you want, if any method is overridden in the child class then it must be called from the child class. If calling class is child class (DerivedClass).
In the above code I want getStaticText() must be called from DerivedClass.
- You may say call DerivedClass::getStaticText(); in place of self::getStaticText(); in BaseClass. But how someone knows while creating BaseClass that which class is going to extend BaseClass.
Then how to achieve this generically?
Solution
Advertising by Adpathway
Contact Us
AllYouCanFind.Club , part of SCAA IMPORT INC.
2949 17 Avenue Southeast, Calgary AB T2A 0P7
Tel : + 1 (514) 800-8693
Mail : Our Email
Business Hours : 9:30 - 5:30




