php函数变量和传递

PHP 支持按值传递参数(默认),通过引用传递参数以及默认参数。也支持可变长度参数列表


引用传递

function add_some_extra(&$string)
{
    
$string .= 'and something extra.';
}


默认参数:

function makecoffee($type "cappuccino")
{
    return 
"Making a cup of $type.\n";
}

默认值必须是常量表达式,不能是诸如变量,类成员,或者函数调用等

Note自 PHP 5 起,传引用的参数也可以有默认值。


Type declarations

Type declarations allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a  TypeError  exception.

e.g.,

function f(C $c) {
    echo 
get_class($c)."\n";
}


 Strict typing

declare(strict_types=1);


try {
    
var_dump(sum(12));
    
var_dump(sum(1.52.5));
} catch (
TypeError $e) {
    echo 
'Error: '.$e->getMessage();
}


可变数量的参数列表

PHP 在用户自定义函数中支持可变数量的参数列表。在 PHP 5.6 及以上的版本中,由 ... 语法实现;在 PHP 5.5 及更早版本中,使用函数 func_num_args()func_get_arg(),和 func_get_args() 

New version:

<?php
function  sum (... $numbers ) {
    
$acc  0 ;
    foreach (
$numbers  as  $n ) {
        
$acc  +=  $n ;
    }
    return 
$acc ;
}

echo 
sum ( 1 2 3 4 );
?>

Old version:

function sum() {
    
$acc 0;
    foreach (
func_get_args() as $n) {
        
$acc += $n;
    }
    return 
$acc;
}

echo 
sum(1234);



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值