Static methods and properties in php

In the last lesson we learnt about Polymorphism,  In this lesson, today we are going to learn about static methods and properties . Before moving further let’s first discuss about the word Static.

Static means immovable or stable. It means when we declare a variable or method as static its value remains the same after its execution.

Syntax to declare a method or property as static.

Static Method Static Variable

 

 

Output : 

Value at first count call is 0
Value at Second count call is 0

In the above example we have not used the static keyword. You can observe that we have called the function twice in the program. Whenever the method counts will be called it will first set the value of $a to zero ($z = 0). then it will make an increment. This is not useful for us as of now. Let’s consider another example.

Output : 

Value at first count call is 0
Value at Second count call is 1

In the above example we saw that the value is getting incremented after calling the method twice and declaring the variable as static.

  • From the above examples it is clear that once a value is declared as static it becomes immovable.
  • Once a variable (property) or methods declared static, we can achieve them without creating object of its class.

How to access static methods and properties outside class?

we can access the static methods and properties methods using scope resolution operator i.e (::) double colon.

Please note while accessing the variable we must add $ sign just after the scope resolution operator.(Ex. classname ::$a). In the example below you can understand this easily.

Output :

10
I was called from static method

 

  • Once a property declared static we can’t access them after creating object of its class.

Output :
Notice: Undefined property: Dummy::$a
I was called from static method

 

How to access static methods and properties without creating object?

To access the class own property and methods within the class, we used to use ($this) keyword earlier.

  • Here to access the class own static property and methods without creating object we use (self) keyword.

Output :
0
3
2

In the above example, we created a Vehicle class where fuel and addFuel  property and method are declared respectively. To get the class own property we used

static public function addFuel($quantity){
  $quantity = (int)$quantity;               // here (int)  converts quantity in integer
self::$fuel += $quantity;
// to get static properties of the class we use self::$fuel ($ important).
}

When to use static method and properties in php

We should not use static method and properties, its not good practice, But when we need to use methods and properties without creating object it is advantageous here.

Static methods and properties are mostly used in Counters, Looping 

 

Leave a Reply

Your email address will not be published. Required fields are marked *