Open In App

Static Function in PHP

Last Updated : 31 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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";
}
  
?>


Output:

The next value is: 1
The next value is: 2
The next value is: 3
The next value is: 4
The next value is: 5

When to define static methods ?
The static keyword is used in the context of variables and methods that are common to all the objects of the class. Therefore, any logic which can be shared among multiple instances of a class should be extracted and put inside the static method. PHP static methods are most typically used in classes containing static methods only often called utility classes of PHP frameworks like Laravel and CakePHP.

Below is the PHP code which shows the use of static methods.

Example: This example illustrates the static method in PHP.




<?php
/* Use of static method in PHP */
  
class A {
      
    public function test($var = "Hello World") {
        $this->var = $var;
        return $this->var;
    }
}
  
class B {
    public static function test($var) {
        $var = "This is static";
        return $var;
    }
}
  
// Creating Object of class A
$obj = new A();
  
echo $obj->test('This is non-static'); 
echo "\n";
echo B::test('This is non-static'); 
  
?>


Output:

This is non-static
This is static

However, a static method doesn’t let you define explicit dependencies and includes global variables in the code that can be accessed from anywhere. This can affect the scalability of an application. Moreover, you will have a tough time performing automated testing on classes containing static methods. Therefore, they should be used for utilities and not for convenience reasons.

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads