2012-09-05 31 views
1

我正在通过call_user_func_array调用一个对象方法,我根据几个参数传递动态字符串参数。确定call_user_func_array的参数

目前,它类似于此:

<?php 
class MyObject 
{ 
    public function do_Procedure ($arg1 = "", $arg2 = "") 
    { /* do whatever */ } 


    public function do_Something_Else (AnotherObject $arg1 = null) 
    { /* This method requires the first parameter to 
      be an instance of AnotherObject and not String */ } 
} 

call_user_func_array(array($object, $method), $arguments); 
?> 

这适用于方法$method = 'do_Procedure'但如果我想叫$method = 'do_Something_Else'方法,需要的第一个参数是AnotherObject一个实例,我得到一个E_RECOVERABLE_ERROR错误。

我如何知道应该传递哪种类型的实例?例如。如果此方法需要一个对象实例,但第一个处理的参数是字符串,那么我如何识别这个以便我可以传递null或者直接跳过该调用?

+1

听起来你是在太动态的函数调用。你不知道你在打什么电话,而且你不知道你传递了什么样的论点......那怎么办? – deceze

+0

那么,我通过控制器对象路由请求,方法表示一个调用句柄。有些调用句柄方法可能需要POST或GET对象包装器,因此应该只有正确的实例。如果字符串被传递,你会得到'试图在一个none对象上调用xxx。 – Daniel

+0

我只想在方法之前验证参数,而不是手动在每个方法上进行参数验证。 – Daniel

回答

2

$ arguments是一个将爆炸到函数参数的数组。如果您拨打do_Something_Else函数,阵列必须为空或第一个元素必须为空或者为AnotherObject的一个实例

在所有其他情况下,您会收到E_RECOVERABLE_ERROR错误。

要找出需要什么参数传递就可以使用Reflectionclass

样品,需要一些工作调整土特产品您的需求:

protected function Build($type, $parameters = array()) 
    { 
    if ($type instanceof \Closure) 
     return call_user_func_array($type, $parameters); 

    $reflector = new \ReflectionClass($type); 

    if (!$reflector->isInstantiable()) 
     throw new \Exception("Resolution target [$type] is not instantiable."); 

    $constructor = $reflector->getConstructor(); 

    if (is_null($constructor)) 
     return new $type; 

    if(count($parameters)) 
     $dependencies = $parameters; 
    else 
     $dependencies = $this->Dependencies($constructor->getParameters()); 

    return $reflector->newInstanceArgs($dependencies); 
    } 

    protected static function Dependencies($parameters) 
    { 
    $dependencies = array(); 

    foreach ($parameters as $parameter) { 
     $dependency = $parameter->getClass(); 

     if (is_null($dependency)) { 
     throw new \Exception("Unresolvable dependency resolving [$parameter]."); 
     } 

     $dependencies[] = $this->Resolve($dependency->name); 
    } 

    return (array) $dependencies; 
    } 
+0

我在想反射看到参数类型。但我不确定这是可能的,这就是为什么我问。而你的回答正是我在我的问题中解释的。 – Daniel

+0

我添加了一个样本 – JvdBerg

+0

'ReflectionParameter :: getClass'正是我所期待的!谢谢。 – Daniel