我有这段代码可以在不同的类之间传递大量变量。目标是内存中不应有任何重复值,因此变量通过引用而不是值传递。
我这里有这个样本。它工作正常,除了以一种方式。只是为了确保该值在内存中不重复,我修改该值或删除该值以确保。
然后我发现取消设置变量有不同的效果,使其为 NULL 有不同的效果。
如果我取消原始变量,那么我仍然从引用变量中获取值。如果我将原始变量设为 NULL,则它不会返回任何内容。
这是代码:
<?php
class a {
private $req;
public function store_request(&$value) {
$this->req = &$value;
}
public function get_request() {
return $this->req;
}
}
class b {
private $json;
private $obj;
public function init_req(&$request) {
$this->obj = new a;
$this->obj->store_request($request);
}
public function get_req() {
return $this->obj->get_request();
}
}
$locvar = 'i am here';
$b = new b;
$b->init_req($locvar);
$locvar = 'now here';
## This will not result empty echo from 'echo $b->get_req();'
//unset($locvar);
## This will result in empty echo from 'echo $b->get_req();'
//$locvar = null;
echo $b->get_req();
?>
注释了 UNSET 和 NULL 行。如果您尝试一次运行一行未注释的代码(我知道这是愚蠢的建议,但仍然:))
谁能告诉这里内部发生了什么?