Php 动态调用类方法Args
我正在做一些事情,需要能够将参数的索引数组传递给方法,就像Php 动态调用类方法Args,php,oop,dynamic,method-invocation,Php,Oop,Dynamic,Method Invocation,我正在做一些事情,需要能够将参数的索引数组传递给方法,就像call\u user\u func\u array的工作方式一样。我会使用call\u user\u func\u array,但它不是一种OOP方法,这是不需要的,它要求方法是静态的,这破坏了目标类的OO 我曾尝试使用ReflectionClass,但没有效果。不能调用类的方法的参数,只能调用构造函数。不幸的是,这是不可取的 因此,我阅读了手册页,查看了ReflectionFunction,但是没有办法实例化该类,将其指向一个方法,然
call\u user\u func\u array
的工作方式一样。我会使用call\u user\u func\u array
,但它不是一种OOP方法,这是不需要的,它要求方法是静态的,这破坏了目标类的OO
我曾尝试使用ReflectionClass
,但没有效果。不能调用类的方法的参数,只能调用构造函数。不幸的是,这是不可取的
因此,我阅读了手册页,查看了ReflectionFunction
,但是没有办法实例化该类,将其指向一个方法,然后使用它来invokeArgs
使用ReflectionFunction
的示例(请记住,此问题标记为PHP5.4,因此使用语法):
$call=new\ReflectionFunction(((ExampleClass())->exampleMethod”);
$call->invokeArgs([“argument1”、“argument2]”);
这在以下情况下失败:
Function (Index())->Index() does not exist
ReflectionMethod Object
(
[name] => Index
[class] => Index
)
使用ReflectionMethod
$call=new\ReflectionMethod(“ExampleClass”、“exampleMethod”);
$call->invokeArgs(新的ExampleClass(),[“argument1”,“argument2]”);
打印(电话);
这在以下情况下失败:
Function (Index())->Index() does not exist
ReflectionMethod Object
(
[name] => Index
[class] => Index
)
参数永远不会传递给方法
预期的结果是:
class-ExampleClass(){
公共函数exampleMethod($exampleArg1,$exampleArg2){
//在这里做点什么
echo“参数1:{$exampleArg1}\n”;
echo“参数2:{$exampleArg2}\n”;
}
}
$array=['exampleArg1Value','exampleArg2Value'];
如果我将$array
传递给ExampleClass->exampleMethod()
的实例,我将只有一个参数,即数组。相反,我需要能够提取各个参数
我在想,如果有一种方法可以在reflector类
上调用reflector函数,我会在船的形状和我的路上,但看起来这是不可能的
有没有人以前用过任何东西来完成这项任务?好的,下面应该可以:
$call = new \ReflectionMethod( "ExampleClass", "exampleMethod" );
$call->invokeArgs( new ExampleClass(), ["argument1", "argument2"] );
print_r( $call );
PHP的次要版本是什么?您使用的是5.4.7吗?我已经编写了自己的依赖项注入器,并且还动态地使用参数构造类。下面是一些代码,可以帮助您继续:
$type = 'ExampleClass';
$reflector = new \ReflectionClass( $type );
if ( !$reflector->isInstantiable() )
throw new \Exception( "Resolution target [$type] is not instantiable." );
$constructor = $reflector->getConstructor();
$parameters = $constructor->getParameters();
此时,您有了一组参数,这些参数是构造所需的。现在,您可以用值替换参数并构造类。由于某种原因,某个地方卡住了
$call = new \ReflectionMethod( "ExampleClass", "exampleMethod" );
$call->invokeArgs( new ExampleClass(), ["argument1", "argument2"] );
现在返回
Argument 1: argument1
Argument 2: argument2
我将试图重现这个问题。它安装在带有php cli和fpm的全新PHP5.4.7上 谢谢!我更倾向于调用一个方法,而不是构造一个类。我将和你分享并让你知道。是的,它应该可以正常工作,你可以在这里轻松检查PHP版本:-注意你的类不是来自其他名称空间或其他什么。