David Sklar在他的PHP Cookbook中解决了何时使用call_user_func_array的问题。因此,要关注 OP 的一条评论:
“......如果要在函数中使用参数,您是否总是需要知道参数?”
这是 call_user_func() 可以派上用场的一个实例:
<?php
function Test(){
$args = func_get_args();
call_user_func_array("printf",$args);
}
Test("Candidates 2014: %s %s %s %s\n","Tom","Debbie","Harry", "Sally");
Test("Candidates 2015: %s %s\n","Bob","Sam","Sarah");
查看实时代码
使用 call_user_func_array() 和 func_get_args() 对,用户定义函数 Test() 可以采用可变数量的参数。
此外,对于聚合方法很有用(请参阅 PHP Cookbook p208-210),如以下简化示例所示:
<?php
class Address {
protected $city;
public function getCity() {
return $this->city;
}
public function setCity($city) {
$this->city=$city;
}
}
class Person {
protected $name="Tester";
protected $address;
public function __construct() {
$this->address = new Address;
}
public function getName(){
return $this->name;
}
public function __call($method, $args){
if (method_exists($this->address,$method)) {
return call_user_func_array( array($this->address,$method),$args);
}
}
}
$sharbear = new Person;
echo $sharbear->setCity("Baltimore");
echo "Name: ",$sharbear->getName(),"\n";
echo "City: ",$sharbear->getCity();
查看实时代码
附录
自 PHP 5.6 起,PHP 支持可变参数函数和参数解包,因此 call_user_func() 和 func_get_args() 可以针对可变参数进行替换,如下所示:
<?php
function Test(...$args){
printf(...$args);
}
$namesT = ["Timmy","Teddy","Theo","Tad"];
$namesB = ["Bobby","Bill","Brad"];
Test("T Names: %s %s %s %s\n",...$namesT);
Test("B Names: %s %s %s\n",...$namesB);
查看实时代码