Static Methods and Properties in PHP with Example

Static Methods and Properties in PHP with Example

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 :

  1. $object= new myClass();
  2. $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 :
  1. class myClass {
  2. static public $variable1 = 5;
  3. static public $variable2 = 2;
  4. static public function getSum() {
  5.     $sum=self::$variable1+self::$variable2;
  6. print "Sum of two variables is " . $sum;
  7. }
  8. }

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(::).

  1. echo myClass::$variable1;
  2. 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.

  1. class myParentClass
  2. {
  3.     public static $variable1=5;
  4. }
  5. class myClass extends myParentClass
  6. {
  7.     public static $variable2=2;
  8.     public $abc =2;
  9. function getSum()
  10. {
  11.     $sum=parent::$variable1+self::$variable2;
  12. print "Sum of two variables is " . $sum;
  13. }
  14. }
  15. echo myClass::$abc; //throw fatal error
  16. myClass::getSum(); // give output Sum of two variables is 7

Make sure don't use $this variable to call static methods.

Why use static methods and properties?

Phone: (+91) 8800417876
Noida, 201301