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.
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