从匿名PHP函数中的父作用域访问变量
在“使用”关键字可以用来绑定变量到特定功能的范围。
使用use关键字将变量绑定到函数的作用域中-
示例
<?php
$message = 'hello there';
$example = function () {
var_dump($message);
};
$example();
$example = function () use ($message) { // Inherit $message
var_dump($message);
};
$example();
//继承的变量的值来自定义函数时的值,而不是调用时的值
$message = 'Inherited value';
$example();
$message = 'reset to hello'; //message is reset
$example = function () use (&$message) { // Inherit by-reference
var_dump($message);
};
$example();
//父范围中更改的值
//反映在函数调用内
$message = 'change reflected in parent scope';
$example();
$example("hello message");
?>输出结果
这将产生以下输出-
NULL string(11) "hello there" string(11) "hello there" string(14) "reset to hello" string(32) "change reflected in parent scope" string(32) "change reflected in parent scope"
最初,“示例”功能首先被调用。第二次,$消息被继承,并且在定义函数时更改其值。$message的值将重置并再次继承。由于在根/父范围中更改了值,因此在调用函数时会反映出更改。
热门推荐
10 老板生日祝福语简短语
11 发给导师的祝福语简短
12 新年简单祝福语简短好看
13 宝宝新年祝福语大全简短
14 送礼祝福语男性生日简短
15 新年简短的英文祝福语
16 双节祝福语简短英文
17 朋友搬迁新房祝福语简短
18 写字生日祝福语简短独特