PHP 5 Static keyword
Static keyword
A static keyword plays an important role in Object Oriented Programming. You can access a static method or property directly without creating any instance of that class. You can create static properties and methods by using static keyword, static properties often call called class properties.
Syntax of static keyword
class MyClass { public static $myProperty; }
PHP5 static property
To access your static properties write a class name first, followed by two colons (::), followed by property.
MyClass::$mypropeties;
Example
<?php class My { static $id= 125; } echo "Your id is:"; print My::$id; ?>
Output
Your id is:125
In the above example, My is the name of the class, $id is a static property. You can access static property with the help of class name.
Static property cannot be accessed through the object of this class using the arrow operator ->. You can be accessed these properties by static method.
Download Source script
you can prevent the unauthorised access by using private and protected access specifier.
Static property with method
<?php class Computer { static $name = "Sony Vaio"; function SetNmae() { print self::$name; } } $obj = new Computer(); $obj->SetNmae(); ?>
You cannot use the static property by static way (My::name). It will generate fatal error. If you want to access the static property using within the class, then you need to use the parent keyword.
Output
Sony Vaio
Parent class static property
Static properties are the best way to share data between the different instance of a class (Object) or another class. You can access the parent class static variable of properties with the help of the parent keyword.
<?php class Computer { public static $name = "Sony Vaio"; } class Laptop extends Computer { public function SetNmae() { return parent::$name; } } $obj = new Laptop(); print $obj->SetNmae() . "
"; ?>
Output
Sony Vaio
You can easily access the parent class static property in the child class by using the parent keyword as shown in the above example.
Static properries are basically uesd to share common data or you can say save memory.