Why and How to use static properties in PHP? OOP in PHP.

A static keyword is very important in object oriented programming. Static methods and properties play a vital role in application design and also in design patterns. So what are static methods and properties?

In general, to access any properties or method of a class we first have to initialize an object of that class. Then we can access any possible properties or method of the class using the object as an agent of the class, right? But in case of static properties and methods, we don't have to initialize an object at all.

Static properties and methods can not be accessed through objects as because they don't belong to object, they belong to the class itself. Any method of the class may change the value of a static properties. And whenever we try to get the value of an static member, we always get it's latest value.

class TestClass{
 static $instance = 0;

 function __construct(){

   throw new Exception('Can not create another instance of this class.');




new TestClass();
In the above code example we declared a static variable in line number 2. Now whenever a new object of the class will try to initiate the __construct() method will be called and it will check for the value of $instance properties. As we said, static properties are properties of the class itself, we called the properties with self:: 

Here, If $instance is having a value, we are throwing an exception and not creating the object.

The target of the above code block is, you can create only one object of the class TestClass. So when the very first object of the class will be created the value of $instance became 1 (line number 7).  And when any other object will attempt to initiate, the class will find value 1 in $instance, and the class will not create and object.

Google Recommends Recommends


Contact Us