PHP封闭变量的作用域 [英] PHP Closures scoping of variables

查看:61
本文介绍了PHP封闭变量的作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看Closures 的PHP示例 rel = noreferrer> http://us1.php.net/manual/zh/functions.anonymous.php

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆