Mik*_*osh 6 php oop dynamic method-invocation
我正在研究一些我需要能够将args的索引数组传递给方法的东西,就像call_user_func_array工作方式一样.我会使用,call_user_func_array但它不是一个OOP方法,这是不受欢迎的,它需要该方法是静态的,这打破了目标类的OO.
我试过用ReflectionClass但无济于事.您不能调用类的方法的参数,只能调用构造函数.遗憾的是,这不是理想的.
所以我进入了手册页并查看了ReflectionFunction但是没有办法实例化类,将它指向一个方法,然后invokeArgs用它.
使用示例ReflectionFunction(记住,这个问题标记为PHP 5.4,因此语法):
$call = new \ReflectionFunction( "(ExampleClass())->exampleMethod" );
$call->invokeArgs( ["argument1", "argument2"] );
Run Code Online (Sandbox Code Playgroud)
这失败了:
Function (Index())->Index() does not exist
Run Code Online (Sandbox Code Playgroud)
使用示例 ReflectionMethod
$call = new \ReflectionMethod( "ExampleClass", "exampleMethod" );
$call->invokeArgs( new ExampleClass(), ["argument1", "argument2"] );
print_r( $call );
Run Code Online (Sandbox Code Playgroud)
这失败了:
ReflectionMethod Object
(
[name] => Index
[class] => Index
)
Run Code Online (Sandbox Code Playgroud)
参数永远不会传递给方法.
期望的结果是:
class ExampleClass() {
public function exampleMethod( $exampleArg1, $exampleArg2 ){
// do something here
echo "Argument 1: {$exampleArg1}\n";
echo "Argument 2: {$exampleArg2}\n";
}
}
$array = [ 'exampleArg1Value', 'exampleArg2Value' ];
Run Code Online (Sandbox Code Playgroud)
如果我传递$array给一个实例ExampleClass->exampleMethod(),我只会有一个参数,这将是一个数组.相反,我需要能够提取个别论点.
我在想,如果有一种方法叫ReflectorFunction上ReflectorClass我会在船的形状和对我的方式,但它不像这是可能的.
有没有人有过他们以前用过的东西?
小智 6
AFAIK,以下应该工作:
$call = new \ReflectionMethod( "ExampleClass", "exampleMethod" );
$call->invokeArgs( new ExampleClass(), ["argument1", "argument2"] );
print_r( $call );
Run Code Online (Sandbox Code Playgroud)
什么小版本是PHP?你在5.4.7吗?
由于某种原因,某处有东西卡住了。
$call = new \ReflectionMethod( "ExampleClass", "exampleMethod" );
$call->invokeArgs( new ExampleClass(), ["argument1", "argument2"] );
Run Code Online (Sandbox Code Playgroud)
现在返回
Argument 1: argument1
Argument 2: argument2
Run Code Online (Sandbox Code Playgroud)
我将尝试重现该问题。它是在带有 php-cli 和 fpm 的全新 php 5.4.7 安装上。
| 归档时间: |
|
| 查看次数: |
5001 次 |
| 最近记录: |