Php 使用_call()将参数传递给接受多个参数但不作为数组的方法
我创建了一个_call()方法来动态加载方法。我想解决的一个问题是_call()生成一个包含调用传递的所有参数的数组。这是我的密码Php 使用_call()将参数传递给接受多个参数但不作为数组的方法,php,Php,我创建了一个_call()方法来动态加载方法。我想解决的一个问题是_call()生成一个包含调用传递的所有参数的数组。这是我的密码 public function __call($method, $params) { if (count($params) <= 1) $params = $params[0]; foreach (get_object_vars($this) as $property => $value) {
public function __call($method, $params)
{
if (count($params) <= 1)
$params = $params[0];
foreach (get_object_vars($this) as $property => $value) {
$class = '\\System\\' . ucfirst(str_replace('_', '', $property)) . '_Helper';
if (strpos($method, str_replace('_', '', $property)) !== false) {
if (!in_array($class, get_declared_classes()))
$this->$property = new $class($params);
$error = $method . ' doesn\'t exist in class ' . $class;
return (method_exists($class, $method) ? $this->$property->$method($params) : $error);
}
}
}
可以当作
$this->->helper->test($param1, $param2);
而不是
$this->helper->test($params);
对于当前的设计,我需要访问如下参数
public function test($params)
{
print_r($params);
echo $param[0];
}
但是我想用一种传统的方式来使用它
public function test($param1, $param2)
{
echo $para1 . " " . $param2;
}
请记住,有些方法需要2个以上的参数,原因是如果我包含不是我创建的传统样式类方法,我需要将所有参数调用转换为数组索引指针
编辑:
根据回答
return (method_exists($class, $method) ? call_user_func_array(array($this->$property, $method), $params) : $error);
这能行吗?看起来你需要。它也很有用
(也可以考虑抛出异常而不是只返回错误字符串)
< P>可以用完成。或者通过从php 5.6开始,您可以通过新的
public function __call($method, $params) {
$result = $this->helper->$method(...$params);
return $result;
}
我只是返回它,而不是像最初那样调用该方法?是的,我还在设计我的函数,然后才得到异常=)
call_user_func_array( array($this->$property, $method), $params );
public function __call($method, $params) {
$result = $this->helper->$method(...$params);
return $result;
}