How to use PHP static methods and attributes. As we all know, the goal of OOP is to write code once, copy, copy, inherit, inherit, and then inherit to make reasonable use of every job, and also facilitate code management. As we all know, the goal of OOP is to write code once, copy, copy, inherit, inherit, and then inherit to make rational use of every job, and also facilitate code management. Find the link where an error occurs. However, sometimes the class we write finds that it is only used once and does not generate multiple instances. At this time, the new method will not only affect the efficiency, but the code is not concise enough.
Therefore, php, which is very emotional, provides us with a convenient and efficient method of static. with it, it will no longer be a problem.
The following describes how to use static and its features.
Hello world:
class hw{ public static function hi(){ return 'Hello World!!!'; }} echo hw::hi();
class hw{ public function hi(){ return 'Hello World!!!'; }} echo hw::hi();
From the above example, we can see that after static and static attributes are used, the method can be called directly from the outside, but for efficiency and other factors, static is recommended.
Static class internal call method
class foo{ private static function c(){ return 'abcd';} public static function a(){ echo self::c();} }foo::a();
When the static keyword is used to restrict the method, you must use self: For internal reference of this class. the above example is clear.
Static property
class foo{public static $a;public static function a(){ self::$a='abcd';}}foo::a();echo foo::$a;
We can also use the static keyword to limit the variable. at this time, the variable will not keep the value of the last negative value.
Static inheritance and use
class foo{public static $a;public static function a(){ return 'abcd';}}class oo extends foo{public static function a(){ echo '1234';}}oo::a();
The inheritance of static is the same as that of ordinary classes, and there is no big difference.
class foo{public static $a;public static function a(){ return 'abcd';}}class oo extends foo{public static function aa(){ echo parent::a();}}oo::aa();
There is only a write difference when using it. it must be parent: Method to reference the parent class method, and cannot use the parent class method directly self:, as shown in the following example, no value is displayed:
class foo{public static $a;public static function a(){ return 'abcd';}} class oo extends foo{public static function aa(){ echo self::a();}}oo::a();
Another simple example
?
Bytes. Which ring...