将 PHP 5.3 匿名函数转换为 5.2 兼容函数 [英] Convert PHP 5.3 anonymous function into 5.2 compatible function

查看:26
本文介绍了将 PHP 5.3 匿名函数转换为 5.2 兼容函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在另一个在 PHP 5.3 中运行良好的函数中有这个匿名函数 $build_tree

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);
                }
    }
}

如何将其转换为 PHP 5.2 兼容代码?

How can I convert this into PHP 5.2 compatible code?

推荐答案

通常,您可以使用对象的方法(回调可以是函数或对象的方法;后者允许您维护状态)来执行此操作.像这样的东西(未经测试):

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);

然而,array_walk_recursive 有一个特殊的特性,它允许我们传递第三个参数,这是一个将被传递到函数的每次调用中的值.虽然值是按值传递的,但我们可以巧妙地使用对象(PHP 5 中的引用类型)来维护状态(来自如何扁平化").一个多维数组到 PHP 中的简单数组?):

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);

这篇关于将 PHP 5.3 匿名函数转换为 5.2 兼容函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆