Static Methods and Properties:


In this Article,I will explain how to use  Static properties or methods in PHP5.

  • To implement static keyword functionality to the attributes or the methods will have to be prefix with static keyword.
  • Static properties or methods can be accessible without needing an instantiation of the class.
  • A property declared as static can not be accessed with an instantiated class object.
  • $this is not available inside the method declared as static.
  • Static properties cannot be accessed using the arrow operator ->. 
  • Static properties can be accessed using the Scope Resolution Operator (::) operator.

                                                  ClassName::$staticvar= $value;


Example:

<?php 
class Box
{
   static private $color;  
   function __construct($value)
   {
  if($value != "")
  {
   Box::$color = $value; 
  }
  $this->getColor();
   }
   public function getColor()
   {
  echo Box::$color ;
   }
    
   static public function StaticMethod() {


        echo self::$color;


    }


}
$a = new Box("RED");
Box::StaticMethod();
$a = new Box("GREEN");
$a = new Box("");
?>


OUTPUT:
RED
RED 
GREEN
GREEN