[php匿名函数调用]PHP匿名函数与注意事项详解

更新时间:2019-11-11    来源:php函数    手机版     字体:

【www.bbyears.com--php函数】


PHP5.2 以前:autoload, PDO 和 MySQLi, 类型约束
PHP5.2:JSON 支持
PHP5.3:弃用的功能,匿名函数,新增魔术方法,命名空间,后期静态绑定,Heredoc 和 Nowdoc, const, 三元运算符,Phar
PHP5.4:Short Open Tag, 数组简写形式,Traits, 内置 Web 服务器,细节修改
PHP5.5:yield, list() 用于 foreach, 细节修改
PHP5.6: 常量增强,可变函数参数,命名空间增强


现在基本上都使用PHP5.3以后的版本,但是感觉普遍一个现象就是很多新特性,过了这么长时间,还没有完全普及,在项目中很少用到。

看看PHP匿名函数:

 'test' => function(){
        return 'test'
},

PHP匿名函数的定义很简单,就是给一个变量赋值,只不过这个值是个function。

以上是使用Yii框架配置components文件,加了一个test的配置。

在另一个模板页面打印试试:

 

test ?>//test
OK.

什么是PHP匿名函数?

看官方解释:

匿名函数(Anonymous functions),也叫闭包函数(closures),允许 临时创建一个没有指定名称的函数。最经常用作回调函数(callback)参数的值。当然,也有其它应用的情况。

匿名函数示例

echo preg_replace_callback('~-([a-z])~', function ($match) {
    return strtoupper($match[1]);
}, 'hello-world');
// 输出 helloWorld
?>

闭包函数也可以作为变量的值来使用。PHP 会自动把此种表达式转换成内置类 Closure 的对象实例。把一个 closure 对象赋值给一个变量的方式与普通变量赋值的语法是一样的,最后也要加上分号:

匿名函数变量赋值示例


$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};
 
$greet('World');
$greet('PHP');
?>
闭包可以从父作用域中继承变量。 任何此类变量都应该用 use 语言结构传递进去。

从父作用域继承变量

$message = 'hello'
 
// 没有 "use"
$example = function () {
    var_dump($message);
};
echo $example();
 
// 继承 $message
$example = function () use ($message) {
    var_dump($message);
};
echo $example();
 
// Inherited variable's value is from when the function
// is defined, not when called
$message = 'world'
echo $example();
 
// Reset message
$message = 'hello'
 
// Inherit by-reference
$example = function () use (&$message) {
    var_dump($message);
};
echo $example();
 
// The changed value in the parent scope
// is reflected inside the function call
$message = 'world'
echo $example();
 
// Closures can also accept regular arguments
$example = function ($arg) use ($message) {
    var_dump($arg . ' ' . $message);
};
$example("hello");
?>

以上例程的输出类似于:


Notice: Undefined variable: message in /example.php on line 6
NULL
string(5) "hello"
string(5) "hello"
string(5) "hello"
string(5) "world"
string(11) "hello world"


php中的匿名函数的注意事项

在php5.3以后,php加入匿名函数的使用,今天在使用匿名的时候出现错误,不能想php函数那样声明和使用,详细看代码

$callback=function(){
  return "aa";
};
echo $callback();
 这是打印出来是aa;

看下面的例子:

echo $callback();
$callback=function(){
  return "aa";
};
 这是报错了!报的错误时:

Notice: Undefined variable: callback in D:\php\www\zf2\public\04.php on line 9
Fatal error: Function name must be a string in D:\php\www\zf2\public\04.php on line 9

$callback为未声明,

但是使用php自己声明的函数都不会报错的!

function callback(){
  return "aa";
}
echo callback();  //aa
 
echo callback();  //aa
function callback(){
  return "aa";
}
 这两个都打印出来aa;

在使用匿名函数的时候,匿名函数当做变量,须提前声明,js中也是这样的!!!!!

本文来源:http://www.bbyears.com/jiaocheng/78527.html