- 引用参数
$name = "eko";function chang_name(&$name){ $name .= '_after_change';} chang_name($name); //会改变原有参数$nameecho $name;
- 参数类型声明
function test(array $arr){ for ($i=0; $i'; }}test('hello'); 报错interface Animal { function eat(); function sleep();}class Cat implements Animal{ public function eat(){ echo "cat eat fish"; } public function sleep(){ echo "cat is sleeping"; }}function fn(Animal $animal){ echo $animal -> eat();}fn(new Cat());
- 可变参数
function fn(){ $arg_nums = func_num_args(); //获得参数个数 echo "此时传入 $arg_nums 个参数"; echo ""; $arr_args = func_get_args(); //获得所有参数,返回数组 echo gettype($arr_args) .""; //输出array foreach ($arr_args as $arg) { echo $arg.""; } $arg = func_get_arg(0); //获得第0个参数 echo $arr_arg;}fn('hello',123);
//在PHP5.6以上版本中,可以用拓展运算符代替可变参数function fn(...$args){ echo "input ".count($args)." arguments"; echo ''; for ($i=0; $i'; }}fn('hello','word',123);fn(...['hello','word',123]); //结果同上//如果有多个参数,可变参数必须放在最后function fn($name,...$args){ echo $name .' '; for ($i=0; $i '; }}fn('kitty','yellow','miao');
- 返回类型
//php7 中支持函数返回值类型声明function sum(...$args):int{ $sum = 0 ; foreach ($args as $value) { $sum += $value; } return $sum; //return 'hello'; //报错,Return value of sum() must be of the type integer}echo sum(1,2,3,4,5);
- 匿名函数 (闭包函数 Closure)
echo preg_replace_callback('~-([a-z])~', function ($match) { return strtoupper($match[1]);}, 'hello-world');//输出 helloWorld