【问题标题】:PHP 5.4.17 alternative for the "... operator"“...运算符”的 PHP 5.4.17 替代方案
【发布时间】:2017-06-21 19:28:40
【问题描述】:

我想知道是否有人知道 PHP 5.6.x 和更高版本 ... 运算符(或我相信它称为 splat 运算符)的替代方案。

我目前在我的 PHP 7 版本中所做的是:

$this->callAction(
...explode('@', $this->routes["authControllers"][$this->routes["uri"][$uri]])
);

callAction() 函数接受 2 个参数 callAction($controller, $action) 但现在我需要将代码降级到 PHP 5.4.17。

【问题讨论】:

  • PHP 5.4 已停止支持将近两年,因此运行起来非常不安全。也就是说,旧方法是使用php.net/func_get_args
  • 谢谢,我会看看 func_get_args。是的,我知道它已经不支持退出一段时间了,但是我的老师没有更新他的本地服务器:/
  • 要么爆炸成一个数组并传递01,要么使用call_user_func_array()

标签: php php-7 php-5.4


【解决方案1】:

虽然 splat 运算符 ... 类似于 call_user_func_array()

call_user_func_array(array($this,'callAction'),
                     explode('@', $this->routes["authControllers"][$this->routes["uri"][$uri]]));

我认为传递所需的参数会更有意义:

list($controller, $action) = explode('@', $this->routes["authControllers"][$this->routes["uri"][$uri]]);
$this->callAction($controller, $action);

【讨论】:

  • 感谢您的回复
【解决方案2】:

我认为等效的 PHP5 代码是 call_user_func_array(array($this,'callAction'),(explode('@', $this->routes["authControllers"][$this->routes["uri"][$uri]])));

编辑:但如果 callAction 总是采用 2 个参数,你可以这样做

$args=explode('@',$this->routes["authControllers"][$this->routes["uri"][$uri]]));
$this->callAction($args[0],$args[1]);

但是如果是这样的话,我想知道为什么 php7 代码会与... 发生冲突,我认为那是为了可变数量的参数? (就像 call_user_func_array 一样。对于一个接受可变数量参数的函数的例子,请参阅var_dump

【讨论】:

  • 感谢您的回复
猜你喜欢
  • 2019-01-14
  • 1970-01-01
  • 1970-01-01
  • 2011-12-29
  • 1970-01-01
  • 1970-01-01
  • 2013-02-10
  • 2017-05-04
  • 1970-01-01
相关资源
最近更新 更多