将方法传递给array_walk时出错

时间:2014-06-29 10:41:18

标签: php arrays

我一直看到有关类似问题的多个问题,但是,我不记得看到一个关于我的问题,因为我无法真正“实施”另一个解决方案来解决我的问题,所以我问你们,如何正确地将类方法传递给__construct中的函数,或者如果它甚至可以在类启动之前传递一个。

因此,当我启动课程A时,我需要增加一些配置值,以便设置它们并使其可用。

function __construct(){
    require 'configs/production.php';

    function increase(&$value,$key){
        $value += DB::$speed * 0.05 * $value;
    }

    array_walk($production,'increase');

    $this->production = $production;
}

好的,这是有效的,但是,我想将increase定义为public function,以便将来可以使用。因此,无论我如何传递函数,使用它都会给我一个错误。

function __construct(){
    require 'configs/production.php';

    array_walk($production,callable 'increase'); // gives error
    array_walk($production,$this 'increase'); // gives error too
    array_walk($production,A 'increase'); // gives error again
    array_walk($production,$this->increase); // is of course undefined
    array_walk($production,$this-> increase()); // of course, lacking paramas

    $this->production = $production;
}

public function increase(&$value,$key){
    $value += DB::$speed * 0.05 * $value;
}

请记住,我在班级A内。我试图使用类型提示,但是,OtherClass $ var应该可以工作,我应该如何从同一个对象发送一个方法。

dev / production上的PHP版本:相同,5.5.11

2 个答案:

答案 0 :(得分:1)

要将类方法传递给函数,请使用array(object, methodname)

array_walk($production, array($this, 'increase'));

对于静态方法,请使用array(classname, methodname)

答案 1 :(得分:1)

首先,你陷入了认为PHP允许嵌套函数的常见陷阱;它没有,它只是让你随时定义全局功能。如果你调用它两次,你的第一个构造函数会出错,因为它会在运行时定义全局函数increase

其次,您需要使用正确的语法将方法作为回调传递,即array($object, $method_name)。因此,在您的情况下,array_walk($production, array($this, 'increase'));或使用短数组语法array_walk($production, [$this, 'increase']);。 PHP手册有a page explaining this, with examples