Generally, in WEB applications, it is difficult for us to use some advanced (or unique) usage of classes to learn how to use static methods. Static method definition
It is easy to define the static method. before declaring the keyword function, add static, for example:
class A { static function fun() { // do somathing } }
Static method usage
It is similar to a static variable and does not need to be instantiated. it can be called directly using:. for example:
A::fun()
Comparison of common methods
Because the call to a static method does not need to be instantiated, an error occurs when you reference the attributes or methods of the class in the static method, that is, self and $ this are incorrect.
class MyClass{ public $num = 5; function __construct() { $this->num = 10; } function fun_1() { echo "I am a public method named fun_1.\n"; echo "The num of object is {$this->num}.\n"; } static function fun_2() { echo "I am a static method named fun_2.\n"; } function fun_3($n) { echo "The arg is {$n}\n"; }}$m = new MyClass;$m->fun_1();$m->fun_2();$m->fun_3('test');MyClass::fun_1();MyClass::fun_2();MyClass::fun_3('test');
Output result:
lch@localhost:php $ php class_method.phpI am a public method named fun_1.The num of object is 10.I am a static method named fun_2.The arg is testI am a public method named fun_1.PHP Fatal error: Using $this when not in object context in /Users/lch/program/php/class_method.php on line 14