Thursday, June 4, 2009

Static members and methods in PHP5

PHP5 supports "static" features, in according to OOP principles.
Note: visibility (private, protected, public) rules for static properties/methods are THE SAME AS common ones.

----------------------------------------------------
Static properties and methods of a class:
  • don't need an instance of the class to use them
  • callable specyfing classname, followed by "::" and the property name (including the "$" symbol ) or method name. Also callable using "self" (instead of the class name) from the same class. Note: private static properties/methods are NOT accessible outside the class
class test
{
public static $v;
private static function
privateSquare($a) { return $a*$a; }
public static function publicSquare($a) {
return self:: privateSquare($a);
}
}
test::$v = 1;
print
test::$v; //1
//print test:: privateSquare(2); //ERROR
print test:: publicSquare(2); //4

furthermore...

----------------------------------------------------
A static properties of a class:
  • is shared between all the objects of the same class
  • you can initiate it using a constant (or other static methods or members)
example: objects (of the same class) counter !

class test2
{
public static $c=0; //initiating
public function __construct()
{
self::$c++; //or test2::$c++
}
}

$a = new test2();
$a = new test2();
print
test2::$c; //2

----------------------------------------------------
A static method of a class:
  • can use static members (in according to the visibility).
  • callable from non-static methods.
  • Note: a static method cannot access non static properties /methods (the class is not instantiated!)
not yet clear ? read carefully the following code
class test2
{
private static $c=0;
public function
__construct() //call internal static
{
self::increment();
}
private static function
increment() //increment static property
{
self::$c++;
}
public static function
getC()
{
return
self::$c++;
}

}

$a = new test2();
$a = new test2();
//print test2::$c; //error (is private !)
//print test2::increment(); //error (is private !)
print test2::getC(); //2

No comments:

Post a Comment

 

PHP and tips|PHP