Inside a static method the pseudo-variable $this is not available. So, it is not possible to call a non static method from inside a static method directly. But using a trick we can call a non static method from a static method.
The trick is as soon as the class object has been instantiated I have stored the pseudo-variable $this into a global variable using a class constructor. Now on the static method call, I have used that stored class instance to access the non static method. See the code segment below:
The above code segment will have the following output:
The trick is as soon as the class object has been instantiated I have stored the pseudo-variable $this into a global variable using a class constructor. Now on the static method call, I have used that stored class instance to access the non static method. See the code segment below:
class PopStar { public function __construct() { $GLOBALS['instance'] = $this; } public static function showBestPopStarName() { return $GLOBALS['instance']->getBestPopStarName(); } public function getBestPopStarName() { return 'Taylor Swift'; } } $obj = new PopStar; echo 'Best Pop Star is: ' . $obj->showBestPopStarName();
The above code segment will have the following output:
Best Pop Star is: Taylor Swift
Comments
Post a Comment