Static Keywords - Understanding of Static Functions , Method and Static Variables in PHP

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. These can also be accessed statically within an instantiated class object.

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.

Static methods are call without  creating an instance of the object,  so the pseudo-variable $this is not available inside methods declared as static.

Static methods are declared with the static keyword:

Syntax - 

<?php
class ClassName {
  public static function staticMethod() {
    echo "Hello World!";
  }
}
?>


To access a static method use the class name, double colon (::), and the method name:

ClassName::staticMethod();

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

Static properties
Static properties are accessed using the Scope Resolution Operator (::) and cannot be accessed through the object operator (->).

No comments:

Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...