确定call_user_func_array的参数


Determine arguments for 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,或者直接跳过调用?

$arguments是一个数组,它将分解为函数的参数。如果调用do_Something_Else函数,则数组必须为空,或者第一个元素必须为null或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;
  }