oursolutionarchitectoursolutionarchitect

Static Function in PHP


In certain cases, it is very handy to access methods and properties in terms of a class rather than an object. This can be done with the help of static keyword. Any method declared as static is accessible without the creation of an object. Static functions are associated with the class, not an instance of the class. They are permitted to access only static methods and static variables. To add a static method to the class, static keyword is used.

public static function test()
{
    // Method implementation
}

They can be invoked directly outside the class by using scope resolution operator (::) as follows:

MyClass::test();

Example: This example illustrates static function as counter.




<?php
/* Use static function as a counter */
  
class solution {
      
    static $count;
      
    public static function getCount() {
        return self::$count++;
    }
}
  
solution::$count = 1;
  
for($i = 0; $i < 5; ++$i) {
    echo 'The next value is: '
    solution::getCount() . "\n";
}
  
?>