Access Non Static Variable From Static Method

Accessing non static variable / property from a static method is not possible. Inside a static method the pseudo-variable $this is not available. As $this is not available inside a static method, the non static variable / property can't be accessed from a static method.

However, using a little trick you can access non a static variable / property from a static method. I got the idea while I was reading a stackoverflow article on how to access non static property from a static method.

The non static variable / property can be accessed from a static method using the following trick:
class PopStar
{
   public $bestPopStar = 'Taylor Swift';
   
   public function __construct()
   {
      $GLOBALS['instance'] = $this;         
   }
   
   public static function showBestPopStarName()
   {
      return $GLOBALS['instance']->bestPopStar;
   }
}   

$obj = new PopStar;
echo 'Best Pop Star is: ' . $obj->showBestPopStarName();
The output of the above code segment will be:
Best Pop Star is: Taylor Swift
As $this is not available inside static method, I am storing $this in a global variable using a constructor. Afterwards inside the static method I am accessing non static property using my global variable.

Comments