如何从类中的数组调用函数


How to call a function from an array, which is in a class

我的问题是,我有一个函数存储在一个数组中,该数组是类的一部分。我想使用 call_user_func() 从这个数组调用一个函数,但我似乎不知道如何编写它。

从不在类中的数组调用函数可以像这样完成。

 $thearray = array( 0 => 'funcone', 1 => 'functwo');
 call_user_func($thearray[0]);

但是,当我尝试对类中的数组执行此操作时,它确实发送了工作,我想因为我需要以某种方式引用该类。我知道你可以从这样的类中调用一个函数:

 call_user_func(array($myclass, 'funcone'));

但我的问题是如何使用call_user_func()从类中的数组调用函数;我希望有人可以帮助我解决这个问题,我有一种感觉,这只是它如何编写的问题。

假设类中的数组是公共的,你可以执行以下操作:

call_user_func(array($myclass, $myclass->thearray[0]));

这回答了你的问题吗?

更新

我尝试了以下方法,它奏效了:

<?php
class Foo {
    public function bar() {
        echo "quux'n";
    }
    public $baz = array('bar');
}
$foo = new Foo();
call_user_func(array($foo, $foo->baz[0]));
shell$ php userfunc.php 
quux

试试这个?

call_user_func(array($this, $thearray[0]));

http://codepad.org/lCCUJYLK

请耐心等待,因为它会有点长。 :)

嗯,我认为我们可以通过PHP的overloading概念来实现这一点,正如你们大多数人所知,它与其他面向对象语言完全不同。

从 PHP 手册的重载页面 - Overloading in PHP provides means to dynamically "create" properties and methods. These dynamic entities are processed via magic methods one can establish in a class for various action types. (http://www.php.net/manual/en/language.oop5.overloading.php)

这种重载魔法在很大程度上取决于 PHP 的魔法方法

如果您看到神奇方法的列表,那么这里可以帮助我们的方法是__call()

每次调用不存在的类方法时,都会调用魔术方法__call。

这将帮助我们防止抛出任何错误/设置任何自定义消息。因此,这里有一个例子,我们可以用来解决上述问题。

<?php
class Test
{
    private $arr = array( 'funcone', 'functwo' );
    public function __call( $func_name, $func_args ) {
        echo "Method called: " . $func_name . "'n";
        echo "Arguments passed: " . $func_args . "'n";
        // this will call the desired function.
        call_user_func( array( $this, $this->arr[ $func_args ] ) );
    }
}
$obj = new Test;
// run the first function in the array
$obj->runTest(0);
?>

希望有帮助。如果这不起作用,我相信可以通过一些试验和错误来调整它。(现在,我说的是PHP,对吧?调整... ;) )