This article mainly introduces the calling of static properties and static methods in object-oriented php For the principles and calling techniques of static attributes and static methods, friends in need can refer to it
The example in this article describes the calling of static attributes and static methods in PHP. Share it with everyone for your reference. The details are as follows:
Here is an analysis of the calling of static attributes and static methods in PHP object-oriented. Regarding their calling (whether they can be called and how to call them), you need to understand where they are stored in the memory, so that it is very easy to understand. Static properties and methods (including static and non-static) have only one location in memory (rather than static properties, there are as many properties as there are instantiated objects).
Example:
?
3 4 7 8 9 16 17 |
<🎜>header("content-type:text/html;charset=utf-8");<🎜> <🎜>class Human{<🎜> <🎜>static public $name = "Little Sister";<🎜> <🎜>public $height = 180;<🎜> <🎜>static public function tell(){<🎜> <🎜>echo self::$name;//Static method calls static attributes, using the self keyword<🎜> <🎜>//echo $this->height;//Wrong. Static methods cannot call non-static properties //Because $this represents an instantiated object, and here is a class, I don’t know which object $this represents } public function say(){ echo self::$name . "I spoke"; //Ordinary methods call static properties, also using the self keyword echo $this->height; } } $p1 = new Human(); $p1->say(); $p1->tell();//The object can access static methods echo $p1::$name;//Object access static properties. You cannot access $p1->name like this //Because the memory location of the static attribute is not in the object Human::say();//Wrong. An error occurs when the say() method has $this; the result can be obtained when there is no $this //But php5.4 or above will prompt ?> |