Paul Draper
Paul Draper

Reputation: 83255

Return a reference in PHP

I am having difficulty understanding PHP's memory model.

Specifically, what how should I change $fn so that $b references $a, and var_dump prints a non-empty array?

$a = array();
$fn = function() use (&$a) {
    return $a;
};
$b = $fn();
$b['a'] = 1;
var_dump($a);

(More generally, do you have a recommended reference for me on when/how to use references?)

EDIT: Examples in other languages, in which a becomes non-empty.

Python:

a = {}
def fn():
    return a;
b = fn()
b['a'] = 1
print a

Javascript

var a = {};
var fn = function() {
   return a;
};
b = fn();
b['a'] = 1;
console.log(a);

Upvotes: 1

Views: 30

Answers (2)

Hamish
Hamish

Reputation: 23316

Like so:

$a = array();
$fn = function &() use (&$a) {
    return $a;
};
$b = &$fn();
$b['a'] = 1;
var_dump($a);

The &() in the second line indicates that $fn should return a reference, and the = &$fn() in line 5 says that $b should be assigned by reference.

Result:

array(1) { ["a"]=> int(1) }

Upvotes: 1

Orangepill
Orangepill

Reputation: 24645

The easiest way to do this would be to make the parameter an object since objects are always passed by reference. An instance of ArrayObject would work in this simple case. I must say though you are either dealing with a use case I've never encountered or there is a fundamental flaw in the design of the structure of your application is this is needed.

<?php
$a = new ArrayObject(array());
$fn = function() use (&$a) {
    return $a;
};
$b = $fn();
$b["a"] = 1;
var_dump($a);

Upvotes: 0

Related Questions