从匿名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 高考祝福语 简短12字