Is it possible to return a reference from a closure in PHP?

陌路散爱 提交于 2019-12-10 12:38:03

问题


In order to return a reference from a function in PHP one must:

...use the reference operator & in both the function declaration and when assigning the returned value to a variable.

This ends up looking like:

function &func() { return $ref; }
$reference = &func();

I am trying to return a reference from a closure. In in a simplified example, what I want to achieve is:

$data['something interesting'] = 'Old value';

$lookup_value = function($search_for) use (&$data) {
    return $data[$search_for];
}

$my_value = $lookup_value('something interesting');
$my_value = 'New Value';

assert($data['something interesting'] === 'New Value');

I cannot seem to get the regular syntax for returning references from functions working.


回答1:


Your code should look like this:

$data['something interesting'] = 'Old value';

$lookup_value = function & ($search_for) use (&$data) {
    return $data[$search_for];
};

$my_value = &$lookup_value('something interesting');
$my_value = 'New Value';

assert($data['something interesting'] === 'New Value');

Check this out:



来源:https://stackoverflow.com/questions/17501165/is-it-possible-to-return-a-reference-from-a-closure-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!