: This article mainly introduces the call of static attributes and static methods in php object orientation. For more information about PHP tutorials, see. The static attributes and call of static methods in php object-oriented are analyzed here. Regarding their calls (whether they can be called or how to call them), you need to understand their location in the memory, which is very easy to understand. Static attributes and methods (including static and non-static attributes) have only one location in the memory (instead of static attributes, the attributes of how many instantiated objects are available ).
Instance:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
header( "content-type:text/html;charset=utf-8" );
class Human{
static public $name = "Xiaomei" ;
public $height = 180;
static public function tell(){
echo self:: $name ; // Call static attributes using the self keyword for static methods
// Echo $ this-> height; // error. Static methods cannot call non-static attributes.
// Because $ this represents the instantiated object, and this is a class, I don't know which object $ this represents
}
public function say(){
echo self:: $name . "I spoke" ;
// Call static attributes using common methods. the self keyword is also used.
echo $this ->height;
}
}
$p1 = new Human();
$p1 ->say();
$p1 ->tell(); // The object can access static methods
echo $p1 :: $name ; // Static properties of object access. $ P1-> name cannot be accessed like this
// Because the memory location of the static attribute is not in the object
Human::say(); // Error. An error occurs when the say () method $ this exists; when $ this exists, the result is returned.
// If php5.4 or above is used, a prompt is displayed.
?>
|
Conclusion:
1. static attributes can be called using self:, static or non-static methods;
2. static methods can call non-static methods and use the self keyword. In php, after a method is self:, it is automatically converted to a static method;
3. static methods cannot call non-static attributes. Because non-static attributes need to be instantiated and stored in objects;
The above describes the php object-oriented static attributes and static method calls, including the content, hope to be helpful to friends who are interested in PHP tutorials.