Is it possible to access outer local variable in PHP?(是否可以在 PHP 中访问外部局部变量?)
问题描述
是否可以在 PHP 子函数中访问外部局部变量?
Is it possible to access outer local varialbe in a PHP sub-function?
在下面的代码中,我想访问内部函数栏中的变量 $l.在栏中将 $l 声明为 global $l 不起作用.
In below code, I want to access variable $l in inner function bar. Declaring $l as global $l in bar doesn't work.
function foo()
{
$l = "xyz";
function bar()
{
echo $l;
}
bar();
}
foo();
推荐答案
你或许可以使用闭包来做到这一点......
You could probably use a Closure, to do just that...
花了一些时间来记住语法,但它看起来像这样:
Edit : took some time to remember the syntax, but here's what it would look like :
function foo()
{
$l = "xyz";
$bar = function () use ($l)
{
var_dump($l);
};
$bar();
}
foo();
而且,运行脚本,你会得到:
And, running the script, you'd get :
$ php temp.php
string(3) "xyz"
一些注意事项:
A couple of note :
- 你必须在函数声明之后放一个
;! - 你可以通过引用
use变量,在它的名字前加上一个&:use (& $l)
- You must put a
;after the function's declaration ! - You could
usethe variable by reference, with a&before it's name :use (& $l)
更多信息,作为参考,你可以看看手册中的这个页面:匿名函数
For more informations, as a reference, you can take a look at this page in the manual : Anonymous functions
这篇关于是否可以在 PHP 中访问外部局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否可以在 PHP 中访问外部局部变量?
基础教程推荐
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何替换eregi() 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
