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

查看:76
本文介绍了将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天全站免登陆