我有两个类:
class A {
function __construct() {
$B = new B;
$ArgumentReflection = new ReflectionMethod($B, "b");
$ArgumentArray = array();
foreach($ArgumentReflection->getParameters() as $ArgumentName) {
if(isset($Request[$ArgumentName->name])) {
$ArgumentArray[$ArgumentName->name] = $_REQUEST[$ArgumentName->name];
}
}
}
}
class B {
function b($one, $two, $three) {
...
}
}
这是一个简化的示例。这个想法是,我可能想在多个方法中定义多个函数,并使用不同数量的参数调用它们。我需要找到如何调用该方法并传递它的解决方案,例如,需要$_REQUEST
变量。例如,如果我在 B 类中有三个函数,如下所示:
class B {
function a($seven, $six) {
}
function b($one, $two, $three) {
}
function c($zebra, $cat, $monkey) {
}
}
如果我"a"
传递给反射方法,我希望函数a
像这样调用:$B->a($_REQUEST["seven"], $_REQUEST["six"])
。如果我通过"b"
,那么像这样:$B->b($_REQUEST["one"], $_REQUEST["two"], $_REQUEST["three"]);
等等。
令人讨厌的是,php 5.6 中可用的...
令牌不是解决方案,
有什么提示吗?感谢
好的,由于 PHP 中的反射记录不多,我发布了我自己的答案,非常感谢 Jack 为我指明了正确的方向。
ReflectionMethod 继承了 invokeArgs 函数,通过该函数可以传递参数数组。所以,最后为了做我想做的事情,我只是在发布的代码后面添加了一行,现在它看起来像这样:
class A {
function __construct() {
$B = new B;
$ArgumentReflection = new ReflectionMethod($B, "b");
$ArgumentArray = array();
foreach($ArgumentReflection->getParameters() as $ArgumentName) {
if(isset($Request[$ArgumentName->name])) {
$ArgumentArray[$ArgumentName->name] = $_REQUEST[$ArgumentName->name];
}
}
$ArgumentReflection->invokeArgs($B, $ArgumentArray);
}
}
class B {
function b($one, $two, $three) {
...
}
}
全部完成。祝大家好运。