如何从变量变量调用类?

时间:2009-12-17 12:44:42

标签: php class methods

我不太确定如何正确地提出这个问题。我想动态调用类中包含的函数(我认为这意味着它们被称为'方法')。

以下是我的代码示例,希望能帮助解释我想要实现的目标。

在这种情况下,$ result返回所有加载的不同模块。然后检查模块的PHP文件是否已包含在其类中,如果该类存在,则尝试直接调用该类。

foreach ($results as $result) {
    $moduleclass_name = 'TestClassName_' . $result->module_name . '::FunctionToCall';
    if (method_exists($moduleclass_name, 'FunctionToCall'))
        $VariableToRetrieve = $modulefunction_name($Parameter1, $Parameter2);
}

这会返回错误

  

“调用未定义的函数   TestClassName_modulename :: FunctionToCall()“

虽然'TestClassName'已被正确声明。

有人能告诉我我做错了吗?

3 个答案:

答案 0 :(得分:3)

你想要的可能是call_user_func_array()

代码看起来与此类似:

call_user_func_array(array($classNameOrInstance, $functionName), array($arg1, $arg2, $arg3));

编辑此外,在您的示例中,您似乎也将函数名称包含在method_exists的类参数中......

答案 1 :(得分:0)

您可以使用call_user_func()来实现您的目标。此外,最好使用is_callable()而不是method_exists()来验证方法是否可调用(方法可能存在,但其可见性可能会阻止其可调用。

foreach ($results as $result) {
    $module_callback = array('TestClassName_' . $result->module_name,'FunctionToCall');
    if (is_callable($module_callback))
        $VariableToRetrieve = call_user_func($module_callback, $Parameter1, $Parameter2);
}

答案 2 :(得分:0)

  1. 我认为它不起作用,因为您的语法可能不支持“静态方法调用”。 我建议你试试Franz的方法call_user_func()

  2. 我在以前的项目中做过类似的事情。

  3. 它被设计为调用实现接口的类,因此已知的方法名称。 我认为修改此代码以使其与您的代码匹配并不困难。

    class CDispatcher {
        public static function GetDispatcher( $module = 'core' ) {
            $class_name = $module . 'Dispatcher';
    
            try {
                // looks for the file associated with the class
                // if the file is not found an exception is raised
                search_class( $class_name );
            } catch ( exception $e ){
                throw new UnkwownModuleException($module);
            }
    
            return new $class_name();
        }
    }
    
    // Then, you call this class :
    $new_instance = CDispatcher::GetDispatcher( $my_module );