If you’re aware of PHP’s static methods and properties, you probably already know that static items are accessible even without creating an instance. What we very often overlook is that these items are also accessible in object instances. It’s never said that static methods and properties are available only to the static scope. In fact, unlike many other languages, PHP allows calling static methods and properties from both static and non static scope. The result is the portability of data between instances. If you declare some properties as static, all object instances will share the properties. Not only that, any changes made from one instance will also be reflected in another instance. So, you could easily share some data between the instances of the same object using static methods and properties.

Let’s see an example:

<?php
 
        class Test
        {
 
            static $count = 0;

	    function __construct() 
	    {
		self::$count++;
	    }
 
            public static function getCount()
            {
                return self::$count."\n";
            }

	    public static function setCount($count)
	    {
		self::$count = $count;
	    }
 
 
        }
 
        $test = new Test;
        print $test->getCount();
	
	$test2 = new Test;
	print $test2->getCount();

	$test2->setCount(100);
	print $test->getCount();

      
?> 


In the above example, we have defined a class named Test. We have defined a constructor which increases the value of the object count when a new instance is constructed. We have also defined two static methods getCount() and setCount().

The output is:

1
2
100

Whenever we have constructed a new instance, the counter has increased. The setCount also worked. Interestingly, we changed the value of $count from one instance and it reflected well on the other. Isn’t that awesome?