PHP 函数的四种传参方式

目录

函数普通的参数

函数参数的默认值

函数参数的引用传值

函数参数的个数不确定的情况


函数普通的参数

  • 对参数和返回值的类型不进行限制
​function test($data)
{
    $type = gettype($data);
    return $type;
}
echo test(array(1,2,3));
#array
echo test('test');
#string

​
  • 对函数的参数类型进行限制,往往需要在参数前面指定参数的类型
function test(array $data)
{
    $type = gettype($data);
    return $type;
}
echo test(array(1,2,3));
#array
echo test('test');
#报错 Fatal error: Uncaught TypeError: Argument 1 passed to test() must be of the type array 
  •  对函数的返回值的类型进行限制
function test(array $data):string
{
    $type = gettype($data);
    return $type;
}
echo test(array(1,2,3));
#array
function test(array $data):int
{
    $type = gettype($data);
    return $type;
}
echo test(array(1,2,3));
#报错 Fatal error: Uncaught TypeError: Return value of test() must be of the type int
  • 同理,也可以把类作为参数类型和返回类型
class Test{
    public $key = array(1,2,3);
    public $value = array();

    public function index(){
        print_r(self::$key);
    }
}
class Test2{
    protected $key = array(1,2,3);
    protected $value = array();
}

function test(Test $data) : Test2
{
    print_r($data);
    print_r($data->key);
    return new Test2();
}
print_r(test(new Test()));
#Test Object ( [key] => Array ( [0] => 1 [1] => 2 [2] => 3 ) [value] => Array ( ) )
#Array ( [0] => 1 [1] => 2 [2] => 3 ) 
#Test2 Object ( [key:protected] => Array ( [0] => 1 [1] => 2 [2] => 3 ) [value:protected] => Array ( ) )

函数参数的默认值

在我们不确定是否使用该参数的情况下,我们可以给该参数一个默认值,默认值的值往往根据需求决定,可以是字符串,布尔值,对象,数组等等。默认值不影响参数类型的传递

function test($data = '1'){
    print_r($data);
    return gettype($data);
}
test();
test('2');
test(array(1,2));
#1
#2
#Array ( [0] => 1 [1] => 2 )

函数参数的引用传值

当我们不需要保留原来的变量只需要新的变量时,往往可以采用引用传值的方式,PHP内置函数有许多引用传值的函数。

function test(&$data,$data1){
    $data = array_merge($data,$data1);
}
$new = array(1,2);
$new1 = array(3,4);
test($new,$new1);
print_r($new);
#Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )

函数参数的个数不确定的情况

当函数的参数不确定的情况下我们可以在函数参数前面加'...',来表示。例如 function test(...$arr){}

function test(  int ...$data){
    foreach ($data as $key=>$value)
    {
        //每一个$value代表一个参数
        var_dump($value) ;
        echo '<br/>';
    }
    echo 'end<br/>';
}

test(1,2,3,4);
test(5,6);
test('a','b');
int(1)
int(2)
int(3)
int(4)
end
int(5)
int(6)
end
Fatal error: Uncaught TypeError: Argument 1 passed to test() must be of the type int

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值