Static (Class Definition) attributes on PHP 5
Static attributes (or methods) can be considered class definition attributes (or methods). They are not accessed from a Class instance but directly from the definition of the class itself, as such they can be accessed directly using the Class_Name::$attribute_name syntax or within the class by the Self::$attribute_name syntax.
The following are a couple of tests of this.
We create a simple class with an Static Attribute
class Static_Test {
public static $counter = 0;
function show_counter() {
echo self::$counter;
}
function increase_counter() {
self::$counter++;
}
}
Accessing the static attribute from the class definition
echo Static_Test::$counter;
Results: 0
Accessing the static attribute within a method from an instance of the Class
$obj1 = new Static_Test;
$obj1->show_counter();
Results: 0
Modifying the attribute value
Static_Test::$counter++;
$obj1->show_counter(); //1
Results: 1
// $obj1->counter++; //Does Nothing.
Results: nothing. Static Attributes can not be accessed directly, even when declared as public.
$obj1->increase_counter();
$obj1->show_counter(); //2
Results: 2. They can be accessed within methods if the syntax used in the method is appropiate.
Accessing the static attribute within a method from another instance of the Class
$obj2 = new Static_Test;
$obj2->increase_counter();
$obj1->show_counter(); //3
Results: 3. Changes done to a static attribute on an instance are reflected across all instances of the class.
A graphical representation of what we’ve done

Accessing Static Attributes from a Child Class
class Static_Child_Test extends Static_Test {
function increase_parent_counter() {
parent::$counter++ ;
}
}
$obj3 = new Static_Child_Test;
$obj3->increase_parent_counter();
$obj2->show_counter(); //4
Results: 4.
Accessing Static Methods
The same holds true for static methods. An example:
class Static_Test2 {
public static function static_method() {
echo 'This is an static Function. Called directly from the Class Definition and not from an Instance of the Class.';
}
}
Static_Test2::static_method();



Leave a Reply
Comment Guidelines
Your Email is required but will not be published.
You can use the following HTML Tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>If you have never commented before your comment will have to be approved before it is shown. Sorry but there is too much comment spam.