Php 确定call\u user\u func\u数组的参数
我通过Php 确定call\u user\u func\u数组的参数,php,oop,Php,Oop,我通过call\u user\u func\u array调用一个objects方法,根据几个参数向其传递动态字符串参数 它目前看起来与此类似: <?php class MyObject { public function do_Procedure ($arg1 = "", $arg2 = "") { /* do whatever */ } public function do_Something_Else (AnotherObject $arg1 = n
call\u user\u func\u array
调用一个objects方法,根据几个参数向其传递动态字符串参数
它目前看起来与此类似:
<?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_other'
方法,该方法要求第一个参数是另一个对象的实例,我会得到一个E_RECOVERABLE_ERROR
错误
我如何知道应该传递哪种类型的实例?例如,如果此方法需要一个对象实例,但第一个处理的参数是字符串,我如何识别它,以便可以传递null,或者干脆跳过调用?$arguments是一个数组,它将分解为函数的参数。如果调用
do\u Something\u Else
函数,数组必须为空,或者第一个元素必须为null,或者是另一个对象的实例
在所有其他情况下,都会出现E\u RECOVERABLE\u错误
错误
要找出需要传递的参数,可以使用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;
}
听起来你的函数调用太过动态了。你不知道你在呼唤什么,你也不知道你在传递什么论据。。。这对任何事情都有什么作用?我通过一个控制器对象来路由请求,方法代表一个调用句柄。一些调用句柄方法可能采用POST或GET对象包装器,因此应该只有正确的实例。如果字符串被传递,您将得到
尝试调用none对象上的xxx
。我只想在方法之前验证参数,而不是手动对每个方法进行参数验证。我正在考虑反射以查看参数类型。但我不确定这是否可能,这就是我问的原因。你的答案正是我在问题中解释的。ReflectionParameter::getClass
正是我想要的!非常感谢。