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!";
}
}
?>
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.
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:
Post a Comment