The detailed code is as follows:
<?php final class Registry { private $data = array(); public function get($key) { return $this->data[$key]; } public function set($key, $value) { $this->data[$key] = $value; } } abstract class Controller { protected $registry; public function construct($registry) { $this->registry = $registry; } } class ControllerCommonHome extends Controller { public function test() { $this->registry->set('load','load'); } } $registry = new Registry(); $con = new ControllerCommonHome($registry); $con->test(); echo $registry->get('load'); ?>
How is the parameter $registry passed in when $conobject is initialized? Pass value Or pass address? If it is passed by value, then when the $con object executes the function test(), it should not affect the original object $registry, but in fact it affects the value of the registry.
But if I change $registry to a simple variable, such as $registry = 123, and assign a value to $registry in the $con object, this time it does not affect the original variable, which is still 123.
Solution
Okay, clone() Constructor. Objects can be cloned. Why clone? I don’t want to change its previous state.
Objects are not general variables. Please see the following section of Google search
Object transfer
Used by PHP5 Zend Engine II, objects are stored in a separate structure Object Store, instead of being stored in Zval like other general variables (in PHP4 objects are stored in Zval like general variables) ). Only the pointer of the object is stored in Zval rather than the content (value). When we copy an object or pass an object as a parameter to a function, we do not need to copy the data. Just keep the same object pointer and let another zval notify the Object Store that this particular object now points to. Since the object itself is located in the Object Store, any changes we make to it will affect all zval structures holding pointers to the object - manifested in the program as any changes to the target object will affect the source object. .This makes PHP objects look like they are always passed by reference, so objects in PHP are passed by "reference" by default and you no longer need to use & to declare them like in PHP4.
I have never thought about this kind of problem before. I only looked for information after seeing your question
The above is the detailed content of Solution to the problem of class constructor parameters in PHP. For more information, please follow other related articles on the PHP Chinese website!