Pages

Saturday, December 7, 2013

Static function,Variable accesibility

Recently one of my co-friends regarding  a programme which made my concepts clear for a static function, variable accessibility outside a class

 <?php  
 final class Hello  
 {  
      private static $greeting='Hello';  
      private static $initialized=false;  
      private static function initialize()  
      {  
           if(self::$initialized)  
           return;  
         self::$greeting='There';  
         self::$initialized=true;  
      }  
     public static function greet()  
     {  
       self::initialize();  
       echo self::$greeting;  
     }  
     public function hello1()  
     {  
       return 'hi';  
     }  
 }  
 echo Hello::hello1();  
 $obj=new Hello();  
 echo "==>";  
 echo $obj->greet();  
 ?>  


this outputs "hi==>There"

A static function though can be called with scope resolution operator via class name directly or from object.

A static variable can only be called from a static function or from a class name via scope resolution operator

And since we can call a static function directly we cannot use $this in the same

for example in static function greet we are calling the
echo self::$greeting;
and not
echo $this->$greeting;

No comments:

Post a Comment