Access Static Variable From a Non Static Method

Accessing static variable or property from a non static method is very easy. As static variable or property cannot be accessed using the class object, it is not possible to access static variable or property through pseudo-variable $this. You can access static variable / property from a non static method in following ways:

a) Using the keyword self with the scope resolution operator
b) Using the keyword static with the scope resolution operator
c) Using the class name with the scope resolution operator

a) Using the keyword self with the scope resolution operator

Let's consider the following code segment where the self has been used to access a static property from a non static method context.
class PopStar
{
   public static $bestPopStar = 'Taylor Swift';
 
 
   public function showBestPopStarName()
   {
      return self::$bestPopStar;
   }
}  

$obj = new PopStar;
echo 'Best Pop Star is: ' . $obj->showBestPopStarName();


b) Using the keyword static with the scope resolution operator

Let's consider the following code segment where the static has been used to access a static property from a non static method context. 
class PopStar
{
   public static $bestPopStar = 'Taylor Swift';
   
   
   public function showBestPopStarName()
   {
      return static::$bestPopStar;
   }
}   

$obj = new PopStar;
echo 'Best Pop Star is: ' . $obj->showBestPopStarName();


c) Using the class name with the scope resolution operator

Let's consider the following code segment where class name has been used to access a static property from a non static method context. 
class PopStar
{
   public static $bestPopStar = 'Taylor Swift';
   
   
   public function showBestPopStarName()
   {
      return PopStar::$bestPopStar;
   }
}   

$obj = new PopStar;
echo 'Best Pop Star is: ' . $obj->showBestPopStarName();


All code segments will have the following output:
Best Pop Star is: Taylor Swift

Comments