Bạn có thể sử dụng một số quirks, hoặc là vượt qua tất cả các đối số như một mảng như ceejayoz gợi ý, hoặc một số mã quá phức tạp phân tách func_get_args() và kết hợp với danh sách mặc định. Không phải sao chép-dán nó, bạn sẽ phải sử dụng các đối tượng và đặc điểm. Cuối cùng, để có thể truyền tất cả các loại giá trị (không bao gồm null hoặc false bằng cách đặt chúng thành tín hiệu cho thay thế param mặc định), bạn sẽ phải khai báo một kiểu đặc biệt dummy DefaultParam. Một dấu trừ khác là bạn phải nhân đôi tên và giá trị mặc định trong khai báo hàm, nếu bạn muốn nhận gợi ý kiểu hoặc trợ giúp trong bất kỳ IDE nào.
class DefaultParam {}
trait multi_arg_functions
{
private static function multi_arg($defaults, $list, $preserve_index = false)
{
$arg_keys = array_slice(array_keys($defaults), 0, count($list));
if ($preserve_index) {
$listed_arguments = array_slice($list, 0, count($arg_keys));
$extras = array_slice($list, count($arg_keys), null, true);
} else {
$listed_arguments = array_splice($list, 0, count($arg_keys));
$extras = &$list;
}
unset($list);
$arguments = array_combine($arg_keys, $listed_arguments);
$arguments = array_filter($arguments, function ($entry) {
return !($entry instanceof DefaultParam); //remove entries that mean default, a special class in this case
});
$arguments = array_merge($defaults, $arguments);
return [$arguments, $extras];
}
}
class b {
use multi_arg_functions;
static function func1($an_argument = 'a value', $another_argument = 'another value', $third_argument = 'yet another value') { //give defaults here to get hints in an IDE
list($args, $extras) = self::multi_arg(//note: duplicate names and defaults
[
'an_argument' => 'a value',
'another_argument' => 'another value',
'third_argument' => 'yet another value!',
], func_get_args());
echo json_encode(['args' => $args, 'extras' => $extras])."\n";
}
}
$default_param = new DefaultParam();
b::func1('value 1');
b::func1('value 2', $default_param, 'third argument');
b::func1('value 3', $default_param, 'third argument', 'fourth argument');
Lưu ý: bằng cách sử dụng preserve_index = true, bạn có thêm đối số để bắt đầu từ chỉ mục gốc của chúng.
Có đề xuất triển khai tính năng này trong php5.5 [https://wiki.php.net/rfc/skipparams](https://wiki.php.net/rfc/skipparams) – Shahid
Còn Syntactic thì sao? https://github.com/topclaudy/php-syntactic – cjdaniel