PHP 匿名函数与注意事项详细介绍

2018-09-07 15:14

阅读:294

  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的配置。

  什么是PHP匿名函数?

  看官方解释:

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

  匿名函数示例

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

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

  匿名函数变量赋值示例

   <?php $greet = function($name) { printf(Hello %s\r\n, $name); }; $greet(World); $greet(PHP); ?>

  闭包可以从父作用域中继承变量。 任何此类变量都应该用 use 语言结构传递进去。

  从父作用域继承变量

   <?php $message = hello // 没有 use $example = function () { var_dump($message); }; echo $example(); // 继承 $message $example = function () use($message) { var_dump($message); }; echo $example(); // Inherited variables value is from when the function // is defined, not when called $message = worldecho $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 = worldecho $example(); // Closures can also accept regular arguments $example = function ($arg) use($message) { var_dump($arg . . $message); }; $example(hello); ?>

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

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

   $callback=function(){ return aa; }; echo $callback();

  打印出来是aa;

  看下面的例子:

   echo $callback(); $callback=function(){ return aa; };

  这时报错了!$callback为未声明,但是使用php自己声明的函数都不会报错的!

   function callback(){ return aa; } echo callback(); //aa echo callback(); //aa function callback(){ return aa; }

  这两个都打印出来aa;

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

  感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


评论


亲,登录后才可以留言!