PHP类不存储引用
如何将引用传递给对象构造函数,并允许该对象更新该引用PHP类不存储引用,php,pass-by-reference,Php,Pass By Reference,如何将引用传递给对象构造函数,并允许该对象更新该引用 class A{ private $data; function __construct(&$d){ $this->data = $d; } function addData(){ $this->data["extra"]="stuff"; } } // Somewhere else $arr = array("seed"=>"data");
class A{
private $data;
function __construct(&$d){
$this->data = $d;
}
function addData(){
$this->data["extra"]="stuff";
}
}
// Somewhere else
$arr = array("seed"=>"data");
$obj = new A($arr);
$obj->addData();
// I want $arr to contain ["seed"=>"data", "extra"=>"stuff"]
// Instead it only contains ["seed"=>"data"]
你必须把它存放在任何地方作为参考
function __construct (&$d) {
$this->data = &$d; // the & here
}
您必须告诉PHP将引用也分配给私有成员
data
,如下所示:
$this->data = &$d;
根据上下文的不同,您可能不希望使用对外部数组的引用,最好将该数组放在处理它的对象中
请注意,构造函数名为
\uuu construct
而不是\uu construction
,这将满足您的要求:
class Test {
private $storage;
public function __construct(array &$storage)
{
$this->storage = &$storage;
}
public function fn()
{
$this->storage[0] *= 10;
}
}
$storage = [1];
$a = new Test($storage);
$b = new Test($storage);
$a->fn();
print_r($a); // $storage[0] is 10
print_r($b); // $storage[0] is 10
$b->fn();
print_r($a); // $storage[0] is 100
print_r($b); // $storage[0] is 100
备选案文1
也可以使用、或,而不是使用数组。因为这些是对象,所以它们将通过引用传递。所有这些都可以实现,因此您可以通过方括号访问它们,例如
$arrayObject = new ArrayObject;
$arrayObject['foo'] = 'bar';
echo $arrayObject['foo']; // prints 'bar'
备选案文2
使用专用类型而不是泛型类型。找出您在该阵列中存储的内容。它是一个配置
?注册表
?A工作单元
?找出它到底是什么。然后将其作为一个对象,并为其提供反映职责的API。然后注入该对象并通过该API访问它
参见本文,参见此处示例,此处我不建议使用此模式;它使您的代码难以预测和理解。谢谢您的回答。我接受了提交的第一个正确答案。