doujie9882 2013-10-14 03:18
浏览 42
已采纳

通过引用修改数组的问题

In PHP, I have the following code (whittled down, to make it easier to read):

class Var {
  public $arr;
  function __construct($arr) {
    $this->arr = $arr;
  }
  function set($k, $v) {
    $this->arr[$k] = $v;
  }
}

class Session extends Var {
  function __construct() {}
  function init() {
    session_start();
    parent::__construct($_SESSION);
  }
}

$s = new Session();
$s->init();
$s->set('foo', 'bar');

var_dump($_SESSION);

At this point, I want $_SESSION to contain 'foo' => 'bar'. However, the $_SESSION variable is completely empty. Why is this the case? How can I store the $_SESSION variable as a property in order to later modify it by reference?

I have tried replacing __construct($arr) with __construct(&$arr), but that did not work.

  • 写回答

1条回答 默认 最新

  • douyouqian8550 2013-10-14 03:22
    关注

    You needed to take care of reference on every variable re-assignment you have.

    So the first place is __construct(&$arr)

    The second is $this->arr = &$arr;

    Then it should work.

    If you didn't put the & in the latter case - it would "make a copy" for the reference you passed in constructor and assign "a copy" to the $this->arr.

    PS: It's really weird to call parent constructor from non-constructor method

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端