参考:什么是变量作用域,哪些变量可以从哪里访问,哪些是“未定义变量";错误? [英] Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?

查看:17
本文介绍了参考:什么是变量作用域,哪些变量可以从哪里访问,哪些是“未定义变量";错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注:这是PHP中处理变量作用域的参考题.请关闭符合此模式的许多问题中的任何一个作为此问题的副本.

Note: This is a reference question for dealing with variable scope in PHP. Please close any of the many questions fitting this pattern as a duplicate of this one.

PHP 中的变量范围"是什么?一个 .php 文件中的变量是否可以在另一个文件中访问?为什么我有时会收到未定义变量" 错误?

What is "variable scope" in PHP? Are variables from one .php file accessible in another? Why do I sometimes get "undefined variable" errors?

推荐答案

什么是变量作用域"?

变量有一个有限的范围",或者可以访问的地方".仅仅因为你在你的应用程序中某处写了一次 $foo = 'bar'; 并不意味着你可以从 引用 $foo>在应用程序中的任何其他地方.变量 $foo 有一定的作用域,只有在同一作用域内的代码才能访问该变量.

What is "variable scope"?

Variables have a limited "scope", or "places from which they are accessible". Just because you wrote $foo = 'bar'; once somewhere in your application doesn't mean you can refer to $foo from everywhere else inside the application. The variable $foo has a certain scope within which it is valid and only code in the same scope has access to the variable.

非常简单:PHP 具有函数作用域.这是 PHP 中存在的唯一一种范围分隔符.函数内的变量仅在该函数内可用.函数外的变量可以在函数外的任何地方使用,但不能在任何函数内使用.这意味着 PHP 中有一个特殊的作用域:global 作用域.在任何函数之外声明的任何变量都在此全局范围内.

Very simple: PHP has function scope. That's the only kind of scope separator that exists in PHP. Variables inside a function are only available inside that function. Variables outside of functions are available anywhere outside of functions, but not inside any function. This means there's one special scope in PHP: the global scope. Any variable declared outside of any function is within this global scope.

<?php

$foo = 'bar';

function myFunc() {
    $baz = 42;
}

$fooglobal 范围内,$baz 内的 local 范围内myFunc.只有 myFunc 中的代码可以访问 $baz.只有代码outside myFunc 可以访问$foo.两者都无法访问另一个:

$foo is in the global scope, $baz is in a local scope inside myFunc. Only code inside myFunc has access to $baz. Only code outside myFunc has access to $foo. Neither has access to the other:

<?php

$foo = 'bar';

function myFunc() {
    $baz = 42;

    echo $foo;  // doesn't work
    echo $baz;  // works
}

echo $foo;  // works
echo $baz;  // doesn't work

范围和包含的文件

文件边界不分隔范围:

a.php

<?php

$foo = 'bar';

b.php

<?php

include 'a.php';

echo $foo;  // works!

适用于 included 代码的规则与适用于任何其他代码的规则相同:只有 function 的单独作用域.出于范围的目的,您可能会考虑包括复制和粘贴代码之类的文件:

The same rules apply to included code as applies to any other code: only functions separate scope. For the purpose of scope, you may think of including files like copy and pasting code:

c.php

<?php

function myFunc() {
    include 'a.php';

    echo $foo;  // works
}

myFunc();

echo $foo;  // doesn't work!

在上面的例子中,a.php 包含在myFunc 中,a.php 中的任何变量都只有局部函数作用域.仅仅因为它们出现a.php 的全局范围内并不一定意味着它们是,它实际上取决于包含/执行代码的上下文.

In the above example, a.php was included inside myFunc, any variables inside a.php only have local function scope. Just because they appear to be in the global scope in a.php doesn't necessarily mean they are, it actually depends on which context that code is included/executed in.

每个新的 function 声明都会引入一个新的作用域,就这么简单.

Every new function declaration introduces a new scope, it's that simple.

function foo() {
    $foo = 'bar';

    $bar = function () {
        // no access to $foo
        $baz = 'baz';
    };

    // no access to $baz
}

课程

$foo = 'foo';

class Bar {

    public function baz() {
        // no access to $foo
        $baz = 'baz';
    }

}

// no access to $baz

范围有什么用?

处理范围问题可能看起来很烦人,但有限的变量范围对于编写复杂的应用程序至关重要!如果您声明的每个变量都可以从应用程序内的其他任何地方使用,那么您将逐步执行所有操作在你的变量上没有真正的方法来跟踪什么改变了什么.您可以为变量指定的合理名称只有这么多,您可能希望在不止一个地方使用变量$name".如果您的应用程序中只能有一次这个唯一的变量名称,您将不得不求助于非常复杂的命名方案,以确保您的变量是唯一的,并且您不会从错误的代码段更改错误的变量.

What is scope good for?

Dealing with scoping issues may seem annoying, but limited variable scope is essential to writing complex applications! If every variable you declare would be available from everywhere else inside your application, you'd be stepping all over your variables with no real way to track what changes what. There are only so many sensible names you can give to your variables, you probably want to use the variable "$name" in more than one place. If you could only have this unique variable name once in your app, you'd have to resort to really complicated naming schemes to make sure your variables are unique and that you're not changing the wrong variable from the wrong piece of code.

观察:

function foo() {
    echo $bar;
}

如果没有作用域,上面的函数会做什么?$bar 来自哪里?它有什么状态?它甚至被初始化了吗?每次都要检查吗?这是不可维护的.这让我们...

If there was no scope, what would the above function do? Where does $bar come from? What state does it have? Is it even initialized? Do you have to check every time? This is not maintainable. Which brings us to...

function foo($bar) {
    echo $bar;
    return 42;
}

变量 $bar 明确地作为函数参数进入这个范围.看看这个函数就很清楚它使用的值来自哪里.然后它显式地返回一个值.调用者有信心知道函数将使用哪些变量以及它的返回值来自哪里:

The variable $bar is explicitly coming into this scope as function argument. Just looking at this function it's clear where the values it works with originate from. It then explicitly returns a value. The caller has the confidence to know what variables the function will work with and where its return values come from:

$baz   = 'baz';
$blarg = foo($baz);

将变量的作用域扩展为匿名函数

$foo = 'bar';

$baz = function () use ($foo) {
    echo $foo;
};

$baz();

匿名函数从其周围的作用域中显式地包含 $foo.请注意,这与 global 范围不同.

The anonymous function explicitly includes $foo from its surrounding scope. Note that this is not the same as global scope.

如前所述,全局作用域有些特殊,函数可以显式地从中导入变量:

As said before, the global scope is somewhat special, and functions can explicitly import variables from it:

$foo = 'bar';

function baz() {
    global $foo;
    echo $foo;
    $foo = 'baz';
}

该函数使用和修改全局变量$foo.不要这样做! (除非你真的真的真的很清楚自己在做什么,即使那样:不要!)

This function uses and modifies the global variable $foo. Do not do this! (Unless you really really really really know what you're doing, and even then: don't!)

这个函数的调用者看到的都是这个:

All the caller of this function sees is this:

baz(); // outputs "bar"
unset($foo);
baz(); // no output, WTF?!
baz(); // outputs "baz", WTF?!?!!

没有迹象表明这个函数有任何副作用,但它确实有.这很容易变成一团糟,因为一些函数不断修改并需要一些全局状态.您希望函数是无状态,只对它们的输入起作用并返回定义的输出,无论您调用它们多少次.

There's no indication that this function has any side effects, yet it does. This very easily becomes a tangled mess as some functions keep modifying and requiring some global state. You want functions to be stateless, acting only on their inputs and returning defined output, however many times you call them.

你应该尽可能避免以任何方式使用全局作用域;当然,您不应该将变量从全局作用域拉"到局部作用域.

You should avoid using the global scope in any way as much as possible; most certainly you should not be "pulling" variables out of the global scope into a local scope.

这篇关于参考:什么是变量作用域,哪些变量可以从哪里访问,哪些是“未定义变量";错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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