从匿名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 生日开业蛋糕祝福语简短