Static Methods and Properties in PHP with Example
Static Methods and Properties is very useful feature in PHP and in this post i am going to tell you about Static Methods and Properties in PHP with example.
If you declare any class property or methods as static then you don't need to create object of class to access that means it can be accessible without creating object of class. You can access directly from class with the help of scope resolution operator (::).
You can use static keyword to define static methods and properties.
If there is no visibility is defined then Static Methods and Properties in PHP will be treated as public.
I here write a simple example and understand you will be familiar with this syntax :
- $object= new myClass();
- $object->variable1=2;
You can see in above example, i change the public variable variable1 in class myClass but now i will give you example of static keywords in PHP 5. Now i will access the properties through the context of the class but make sure methods or properties must be declared static.
Example :
- class myClass {
- static public $variable1 = 5;
- static public $variable2 = 2;
- static public function getSum() {
- $sum=self::$variable1+self::$variable2;
- print "Sum of two variables is " . $sum;
- }
- }
Now you will see in above example i have declared method and properties as static using static keyword.
To access the static method you will use class name with scope resolution operator(::).
- echo myClass::$variable1;
- myClass::getSum();
If you are trying to access regular property by static way then it will throw fatal error.
self
keyword is used to access static property within the class.
If you extends the parent class in child class and want to access parent class property then you can use parent
keyword.
- class myParentClass
- {
- public static $variable1=5;
- }
- class myClass extends myParentClass
- {
- public static $variable2=2;
- public $abc =2;
- function getSum()
- {
- $sum=parent::$variable1+self::$variable2;
- print "Sum of two variables is " . $sum;
- }
- }
- echo myClass::$abc; //throw fatal error
- myClass::getSum(); // give output Sum of two variables is 7
Make sure don't use $this
variable to call static methods.