简体   繁体   English

用PHP返回引用

[英]Return a reference in PHP

I am having difficulty understanding PHP's memory model. 我很难理解PHP的内存模型。

Specifically, what how should I change $fn so that $b references $a , and var_dump prints a non-empty array? 具体来说,我应该如何更改$fn以便$b引用$a ,并且var_dump打印一个非空数组?

$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. 编辑:其他语言中的示例,其中a变为非空。

Python: 蟒蛇:

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

Javascript 使用Javascript

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

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. 第二行中的&()表示$fn应该返回引用,而第5行中的= &$fn()则表明$ b应该通过引用分配。

Result: 结果:

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

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. 在这种简单情况下,可以使用ArrayObject的实例。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM