PHP5 Static Keywords

PHP5 offers a static methods and static member variables.A special kind of method that can be called without instantiating a class.Static methods don’t depend on the properties of a particular instance of a class but belong to the class itself.

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can).

Static methods are executed only when they are called so there is no need of object creation so we can save some memory which object can occupy

  • We can’t access Static properties through the object using the arrow operator ->.
  • Calling non-static methods statically generates an E_STRICT level warning.

Example:

class Cl_static {
static public $var = ‘Bhumi’;        // declare static properties

static function md_static($var){
echo self::$var.”<br/>” ;
self::$var = $var; //To change the value of the $var static property
echo self::$var.”<br/>” ;
}

}
$obj = new Cl_static();
$obj->md_static(“CreativeDev”);
//$obj->var; //Strict Standards: Accessing static property Cl_static::$var as non static – NOT ALLOWED
Cl_static::md_static(“CreativeDev”);

Output:

Bhumi
CreativeDev
CreativeDev
CreativeDev

Share This Post

Post Comment