PHP 进阶之 函数(Function)

  • 引用参数
$name = "eko";
function chang_name(&$name){
    $name .= '_after_change';
}    
chang_name($name);    //会改变原有参数$name
echo $name;
  • 参数类型声明
function test(array $arr){
    for ($i=0; $i <count($arr) ; $i++) { 
        echo $arr[$i] .'</br>';
    }
}
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 "</br>";

    $arr_args = func_get_args();    //获得所有参数,返回数组
    echo gettype($arr_args) ."</br>";   //输出array

    foreach ($arr_args as $arg) {
        echo $arg."</br>";
    }

    $arg = func_get_arg(0);        //获得第0个参数
    echo $arr_arg;
}
fn('hello',123);
//在PHP5.6以上版本中,可以用拓展运算符代替可变参数
function fn(...$args){
    echo "input ".count($args)." arguments";
    echo '</br>';
    for ($i=0; $i <count($args) ; $i++) { 
        echo $args[$i] .'</BR>';
    }
}
fn('hello','word',123);
fn(...['hello','word',123]); //结果同上

//如果有多个参数,可变参数必须放在最后
function fn($name,...$args){
    echo $name .'</br>';
    for ($i=0; $i <count($args) ; $i++) { 
        echo $args[$i] .'</BR>';
    }
}
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

猜你喜欢

转载自www.cnblogs.com/xiaoliwang/p/8990098.html
今日推荐