Just like Static methods, Static properties can be called without having to create a class instance first. The static keyword is used to declare static methods:
static $name="test";
Static properties can be called from outside the class using the class name and the scope resolution operator (::), as seen below:
Consider the following scenario:
<?php class gravity { static $g= 9.8; } // Call static property echo gravity::$g; ?>
Static properties: Self Keyword:
Property can be both static and non-static in a class. The self keyword and double colon (::) can be used to access a static property from a method in the same class.
<?php class gravity { static $g= 9.8; public function staticValue() { return self::$g; } } // static property using function $gr = new gravity(); echo $gr->staticValue(); ?>
Static Property and Inheritance:
The parent keyword inside the child class is used to invoke a static property(Protected/Public) from a parent class.
Let’s see an example below in which the child class is invoking static property of the parent class.
<?php class gravity { static $g= 9.8; } class gr extends gravity { public function Staticvalue() { return parent::$g; } } echo "calling static property directly via child class = "; echo gr::$g; echo "<br>"; echo "calling static property via Staticvalue() method = "; $gr = new gr(); echo $gr->Staticvalue(); ?>