PHP 类不存储引用 [英] PHP class not storing reference

查看:59
本文介绍了PHP 类不存储引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将引用传递给对象构造函数,并允许该对象更新该引用?

How do I pass a reference to an object constructor, and allow that object to update that reference?

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"]

推荐答案

您必须将其存储在任何地方作为参考.

You must store it everywhere as a reference.

function __construct (&$d) {
    $this->data = &$d; // the & here
}

这篇关于PHP 类不存储引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆