This article mainly shares with you the detailed explanation of objects created in PHP, mainly using text and code. I hope it can help everyone.
The creation of objects in PHP is: new class name;
Class A{ public $p1=1; } $o1=new A(); var_dump($o1);
The result is:
It can be seen that the variable $o1 is a Object type of class A. "#1" is a system-internal custom identifier.
When the system is created, what is stored in the variable $o1 is actually the system's internal customized identifier #1, and the corresponding object entity is found through #1 (similar to reference transfer).
After assigning variable $o1 to $o2, change the corresponding p1 value in object o1. At this time, the corresponding p1 value in o2 will also change:
$o2=$o1; $o1->p1=10; echo "<br/>$o2->p1"; var_dump($o2);
When changing the attributes in $o1, the corresponding attributes in $o2 will also change. And the properties of o1 and o2 are the same (in fact, they point to the same object).
The real way is as shown in the figure:
And for reference by valueapplication in class objects :
Class A{ public $p1=1; } $o1=new A(); $o2=&$o1; $o1->p1=10; echo $o1->p1; echo "<br/>"; echo $o2->p1; echo "<br/>"; var_dump($o1); echo "<br/>"; var_dump($o2);
When changing the attribute p1 in object o1, the attributes in o2 will also change. It’s not like our previous understanding of ‘value passing’ and ‘reference passing’.
The specific implementation method is:
So $o2 still exists after unset ($o1).
Class A{ public $p1=1; } $o1=new A(); $o2=&$o1; $o1->p1=10; unset($o1); echo $o1->p1; echo "<br/>"; echo $o2->p1; echo "<br/>"; var_dump($o1); echo "<br/>"; var_dump($o2);
The above is the detailed content of Detailed explanation of creating class objects in PHP. For more information, please follow other related articles on the PHP Chinese website!