Blogger Information
Blog 24
fans 0
comment 0
visits 18503
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
函数类型、返回值以及参数
昔年
Original
502 people have browsed it

 1 . 类型

    自定义函数:用户根据业务需求创建

    系统函数:也叫预定义函数,不必声明直接调用

    可变函数:函数名使用变量表示

    匿名函数(闭包):也叫"闭包"或"函数表达式",常用做回调处理

<?php
//1.自定义函数
    function Sum(float $a,float $b) : float
    {
        return $a + $b;
    }

    echo Sum(4.2,5.6);
    echo '<hr>';

//2.系统函数

    $str = 'fggfmlkfdkdfd';
    echo substr_replace($str,'dddd',2,4);
    echo '<hr>';

//3.可变函数
$funcName = 'Sum';
echo $funcName(4.5,9.1);
echo '<hr>';

//4.匿名函数
$row = 10;
$total = function($column) use ($row) 
{   
    echo '总数:' . $column * $row;
};

$total(10);

demo5.png

2.返回值

    PHP函数默认只能返回一个值,要返回多值时需要进行处理,可以用字符串拼接、数组、json、序列号四种方式来处理进行返回多值

<?php
//1.自定义函数
    function Sum(float $a,float $b) : float
    {
        return $a + $b;
    }

    echo Sum(4.2,5.6);
    echo '<hr>';

//2.系统函数

    $str = 'fggfmlkfdkdfd';
    echo substr_replace($str,'dddd',2,4);
    echo '<hr>';

//3.可变函数
$funcName = 'Sum';
echo $funcName(4.5,9.1);
echo '<hr>';

//4.匿名函数
$row = 10;
$total = function($column) use ($row) 
{   
    echo '总数:' . $column * $row;
};

$total(10);

demom6.png

3.参数类型

- 调用者可以通过参数将数据传递到函数中

- 参数是以逗号分隔的表达式列表

- 参数按照从左到右的顺序求值

    值参数:默认传参形式

    引用传递:改变原始调用参数值 

    默认参数:调用时允许省略的参数

    剩余参数:调用参数数量不确定

<?php
//函数参数

//1.值参数
function demo1(int $a) : int
{
    return $a * $a;
}
$value = 0;
echo demo1($value).'<br>';
echo $value;
echo '<hr>';


//2.引用传递
function demo2(array &$arr) : array
{
    $arr[] = '100';
    return $arr;
}

$arr = [3,5,6,7];
var_dump(demo2($arr));
echo'<br>';
var_dump($arr);
echo '<hr>';

//3.默认参数
function demo3(int $a,$b = 1) : int
{
    if($b == 1){
        return $a;
    }elseif($b == 2){
        return $a * $a;
    }else{
        return $a -10;
    }
}

echo demo3(10).'<br>';
echo demo3(7,2);
echo '<hr>';

//4.剩余参数
function demo4(...$args){
    $len = count($args);
    return array_sum($args) % $len;
}

$arr = [2,4,5,65,6,7,10];
echo demo4(...$arr);

demo7.png

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:还不错, 继续
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!