PHP封闭变量的作用域 [英] PHP Closures scoping of variables
问题描述
我正在查看
I am looking at the PHP example of Closures
on http://us1.php.net/manual/en/functions.anonymous.php
它提供了示例代码
闭包也可以从父范围继承变量。任何此类
变量都必须在函数头中声明。从父作用域继承
变量与使用全局
变量不同。全局变量存在于全局范围内,无论执行什么功能,它都是
。
闭包的父作用域是在其中声明闭包的函数(而不是
一定是从其调用的函数)。请参见下面的
示例:
Closures may also inherit variables from the parent scope. Any such variables must be declared in the function header. Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from). See the following example:
尽管如此,我对此感到困惑。在我看来, $ quantity
和 $ product
变量在Closure函数中不可用。 父级作用域
在这种情况下不是 getTotal()
函数的1个作用域吗?
I am confused as to how this is working though. $quantity
and $product
variables do not seem to me that they would be available inside the Closure function. Wouldn't the Parent Scope
be 1 scope up in this case the getTotal()
function?
推荐答案
您误解了函数签名。 $ quantity
和 $ product
是将在调用函数时传递给函数的常规参数,但实际上并没有存在于父作用域中,并不意味着存在。 使用($ tax,& $ total)
是父作用域中的封闭变量。
You're misunderstanding the function signature. $quantity
and $product
are the regular arguments that will be passed into the function when it's called, they indeed do not exist in the parent scope and aren't meant to. use ($tax, &$total)
are the closed over variables from the parent scope.
$foo = 'foo'; // closed over variable
// vvvv
$func = function ($bar) use ($foo) {
// ^^^^
// regular function argument
return $foo . $bar;
};
echo $func('baz'); // "foobaz"
这篇关于PHP封闭变量的作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!