Home > Article > Backend Development > Memory location analysis of static attributes and methods in PHP object-oriented, object-oriented static_PHP tutorial
The example of this article analyzes the memory location of static properties and methods in PHP object-oriented. Share it with everyone for your reference. The details are as follows:
static The memory location of static properties -> class, not object. Let’s do a test to prove it
<?php header("content-type:text/html;charset=utf-8"); class Human{ static public $name = "小妹"; public $height; public function tell(){ } } echo Human:$name; //不依赖于对象,就能直接访问。因为静态属性的内存位置是在类里,而不是对象。 $p1 = new Human(); $p2 = new Human(); print_r($p1); echo $p1::$name = "夫人"; //在$p1对象上改变静态属性的值,那$p2对象也会相应的改变。 echo $p2::$name; ?>
The output results can be seen:
1. echo Human:$name: After the class is declared, there is a static attribute, which does not depend on the object. Therefore, there is only one static attribute (meaning that in memory, the storage location is not in the object; if it is in the object, then instantiating an object will have the corresponding static location, such as the height attribute);
2. print_r($p1): The print result only has the height attribute, but no name;
3. After the value of a static attribute changes, the attribute value of all objects will be affected.
Methods, whether static or ordinary, exist in the class memory space. The proof is also very simple, just create a new object and print_r (object).
I hope this article will be helpful to everyone’s PHP programming design.