Analyze. Act. Achieve.
Kurinchilion KURINCHILION Analyze. Act. Achieve.

News

PHP5 - Being Static

Class properties

This is another name for properties (or methods) declared static inside classes as these properties belong to a class and not to any instance/object.

The keyword 'static' is used to define static properties.

Sample program: class ClassA{ static $variableA; static $variableB = 10; }

To print the value of variableB, you will use

echo "Variable B in ClassA = " . ClassA::$variableB;

To further expand on this topic,

Print static variables value from within the class class ClassA{ static $variableA; static $variableB = 10;

function __construct(){ echo "To print variableB inside class ". self::$variableB; } }

As static properties or methods are not tied to an object, we can call them without instantiating a class. Depending on the place from where the call to the static member is made, we use the identifier "self" or the name of the class with "::" or not "$this".

class classB{ static $classVarA = 5;

static function memberA(){ echo "value of classVarA ". self::$classVarA; }

} To display the variable of classVarA from outside the class, you can call the static method by

classB::memberA();

If you have another class "classC" inheriting "classB", then you can access the property/method in ClassB using "parent::" identifier as below

classC extends classB{

function __construct(){ echo "Variable from B " . parent::$classVarA; }

}