Blogger Information
Blog 29
fans 0
comment 0
visits 19493
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
默认参数,剩余参数,匿名函数,call_user_func_array-2019年7月30日
blog
Original
1028 people have browsed it

一.默认参数

默认参数:在函数定义过程时,提前为函数的参数设置好了默认值,在函数调用但未提供实参时,所采用的赋值方式

实例

<?php

function sum($a=10,$b=20){
    return $a*$b;
}
echo sum()."<br>";
echo sum(20)."<br>";
echo sum(20,30)."<br>";

运行实例 »

点击 "运行实例" 按钮查看在线实例

1.png

二.剩余参数

剩余参数:在函数参数设置中以 ...变量名方式设置的形参,剩余参数可代表未被直接赋值的所有实参,且实参之间以数组的形式存储在一起

实例

<?php

function sum($a,$b,...$c)
{
    return $a+$b+array_sum($c);
}
echo sum(1,2,3,4,5,6,7,8,9);

运行实例 »

点击 "运行实例" 按钮查看在线实例

1.png

三、函数内访问外部变量

实例

<?php

$food="食物";
$eat=function()
{
    global $food;
    return "我要吃".$food;
};
echo $eat()."<hr>";

$water="可乐";
$drink=function()
{
    $GLOBALS['water'];
    return "我要喝".$GLOBALS['water'];
};
echo $drink()."<hr>";

const GAME1="q";
define("GAME2","w");
$game=function()
{
    return "game1:".GAME1."|||GAME2:".GAME2;
};
echo $game();

运行实例 »

点击 "运行实例" 按钮查看在线实例

1.png

四.匿名函数,调用外部数据

匿名函数:也叫闭包函数 ,它允许临时创建一个没有指定名称的函数。最经常用作回调函数参数的值。

使用use 关键字,调用外部数据

实例

<?php

$password="123456";
$demo1=function() use ($password){
    return "我的密码是:".$password;
};
echo $demo1();

运行实例 »

点击 "运行实例" 按钮查看在线实例

1.png

五.回调

函数的调用常见的有传统的方式和只用函数回调的方式 

常用的两个方法 call_user_func( ) 和call_user_func_array()

与call_user_func()相比call_user_func_array( )更为常用

实例

<?php

function add($a,$b){
    return $a+$b;
}
//传统方式
echo add(1,2)."<hr>";
//回调方式1 call_user_func("函数名",函数参数)
echo call_user_func('add',5,10)."<hr>";
//回调方式2 call_user_func_array("函数名",参数数组)
echo call_user_func_array("add",[100,200])."<hr>";
//也可以调用系统函数
echo call_user_func_array('print_r', [[1,2,3,4]])."<hr>";

class A
{
    public function sum($a, $b) {
        return $a + $b;
    }

    public static function mul($a, $b) {
        return $a * $b;
    }
}
$a=new A;
echo $a->sum(1,2)."<hr>";
// 还可以将对象/类中的方法以回调的方式来执行
echo call_user_func_array([($a),'sum'],[100,200])."<hr>";
echo call_user_func_array(['A','mul'],[10,30])."<hr>";

运行实例 »

点击 "运行实例" 按钮查看在线实例


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
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!