PHP函数技巧篇

可变参数

Php提供3个函数用于检索在函数中所传递的参数。

$array = func_get_args();	//返回一个提供给函数的所有参数的数组
$count = func_num_args();		//	返回提供给函数的参数数目
$value = func_get_arg(arg_num);	// 返回来自一个index的特定参数

这样函数的返回值不能直接作为一个参数给其他的函数使用,可以先赋值给变量,然后传给参数

例子(返回参数和)

function countList(){
    if (func_get_args() == 0)
        return false;
    else{
        $count = 0;
        for ($i=0; $i<func_num_args(); $i++){
            $count += func_get_arg($i);
        }
        return $count;
    }
}

echo countList(1, 5, 9);    //输出15

返回值的引用

例子

$name = array('fred', 'barney','wilma', 'betty');
function &findOne($n){
    global $names;
    return $names[$n];
}
$person = &findOne(1);
$person = 'barnetta';   // 改变了$names[1]

说明

这里findOne返回的是name[1]的别名,而不是name[1]值的拷贝,person和name[1]所指的为同一块内存。尝尝被用于高效的从函数返回大量值,但是php写时复制机制的存在,反而有时候会使引用比返回值的速度要慢。

可变函数

定义

基于变量的值调用函数($$结构),可以在变量名后面增加一个括号来调用函数,变量值就是函数名。

例子

$which();   //如果$witch的值是first,名为first的函数就会被调用

notice

如果没有这个变量对应存在的函数,代码执行时会产生一个运行时错误,function_exists($witch)可以判断此函数是否存在

匿名函数:

<?php
$message = 'hello';
$example = function () {
    var_dump($message);
};
echo $example();
// Notice: Undefined variable: message in /example.php on line 6
// 因为匿名没有继承变量

// 继承 $message
$example = function () use ($message) {
    var_dump($message);
};
echo $example();    //hello
// 匿名函数继承变量,变量存在,调用成功

$message = 'world';
echo $example();    //hello
// 函数中变量的值,在定义函数时被定义,而不是被调用


$message = 'hello';
$example = function () use (&$message) {
    var_dump($message);
};
echo $example();    //  hello
$message = 'world';
echo $example();    //world
//继承引用, 当变量值在父类中被改变,函数会被影响

$example = function ($arg) use ($message) {
    var_dump($arg . ' ' . $message);
};
$example("hello");  // hello world
// 闭包也可以接受其他正常参数
?>
原文地址:https://www.cnblogs.com/alihenaixiao/p/5754456.html