美文网首页
PHP函数参数里三个点含义和用法,?array $data =

PHP函数参数里三个点含义和用法,?array $data =

作者: wyc0859 | 来源:发表于2019-10-10 17:11 被阅读0次
function(...$args) //三个点是什么含义

一种语法糖: 可以通过...将函数参数存储在紧接的可遍历的变量中。

function add($a, $b, $c)
{
    return $a + $b + $c;
}
 $num=[2, 3];
echo add(1, ...$num);       //6
class Index
{
 public function index()
    {
        $num=[1, 2, 3];
        $this->first($num);
    }


    function first($num)   
    {
        echo 'first:<br/>';
        $this->second(...$num);
    }

    public function second($a,$b,$c)
    {
        echo 'second:<br/>';
        var_dump($a,$b,$c);
    }
first()的参数如果是...$num会报错,除非传入的时候就是...$num,或者second用($a)接收
   /*
   public function second($a)
    {
        echo 'second:<br/>';
        var_dump($a);  //array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }
    }*/
}
结果:
first:
second:
int(1) int(2) int(3)
public function index()
    {
        $a="1";
        $b="2";
        $c="3";
        $this->first(compact("a","b","c"));
    }

    function first($num)   
    {
        echo 'first:<br/>';
        var_dump($num);
//array(3) { ["a"]=> string(1) "1" ["b"]=> string(1) "2" ["c"]=> string(1) "3" }
        //$this->second(...$num); //这里会报错,因为这里不是变量
    }

php7 加入了类型限定
function test(array $name) //可以看出是限定必须是数组
function test(?array $name) //限定必须是数组或null
function test(?array $name=[1])
限定必须是数组或null,无论是传入数组还是null都不会显示[1] 没明白后面这个默认值是啥意思

 public function index()
    {
        $this->test([3,4,5]);
        $this->test(null);  //这里改为false不行,只能是null
    }
    
    function test(?array $name=[1])
    {
        var_dump($name);
    }

相关文章

网友评论

      本文标题:PHP函数参数里三个点含义和用法,?array $data =

      本文链接:https://www.haomeiwen.com/subject/fsdapctx.html