Convert PHP 5.3 anonymous function into 5.2 compatible function

怎甘沉沦 提交于 2019-12-12 13:43:46

问题


I have this anonymous function $build_tree within another function that works fine in PHP 5.3

function nest_list($list) {
$index = array();
index_nodes($list, $index);

$build_tree = function(&$value, $key) use ($index, &$updated) {
    if(array_key_exists($key, $index)) {
        $value = $index[$key];
        $updated = true;
     todel($key); }
};

do {
    $updated = false;
    array_walk_recursive($list, $build_tree);
} while($updated);

return $list;
}

function index_nodes($nodes, &$index) {
    foreach($nodes as $key => $value) {
    if ($value) {
        $index[$key] = $value;
        index_nodes($value, $index);
                }
    }
}

How can I convert this into PHP 5.2 compatible code?


回答1:


Generally, you could do this using an object's method (callbacks can be either a function, or an object's method; the latter allows you to maintain state). Something like this (not tested):

class BuildTree {
    public $index, $updated = false;
    public function __construct($index) {
        $this->index = $index;
    }
    function foo(&$value, $key) {
        if(array_key_exists($key, $this->index)) {
            $value = $this-.index[$key];
            $this->updated = true;
         todel($key); }
    }
}

do {
    $build_tree_obj = new BuildTree($index);
    array_walk_recursive($list, array($build_tree_obj, 'foo'));
} while($build_tree_obj->updated);

However, array_walk_recursive has a special feature that allows us to pass a third argument, which is a value that will be passed into every call of the function. Although the value is passed by value, we can cleverly use objects (reference types in PHP 5) to maintain state (from How to "flatten" a multi-dimensional array to simple one in PHP?):

$build_tree = create_function('&$value, $key, $obj', '
    if(array_key_exists($key, $index)) {
        $value = $index[$key];
        $updated = true;
     todel($key); }
');

do {
    $obj = (object)array('updated' => false);
    array_walk_recursive($list, $build_tree, $obj);
} while($obj->updated);



回答2:


I don't think this is possible without changing the way the function is called, because there is no mechanism in PHP 5.3 for a lambda function to change a variable from the scope it is called in (in this case $updated).

You could return $updated like this:

$build_tree = create_function('&$value,$key,$updated','
    $index = '.var_export($index).';
    if(array_key_exists($key, $index)) {
        $value = $index[$key];
        $updated = true;
     todel($key); }
     return $updated;
');

but then you have to call it like this:

$updated = $build_tree('the value','the key',$updated);


来源:https://stackoverflow.com/questions/8236452/convert-php-5-3-anonymous-function-into-5-2-compatible-function

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