简体   繁体   English

PHP变量生命周期/范围

[英]PHP variable life cycle/ scope

I'm a Java developer and recently I'v been tasked with PHP code review. 我是Java开发人员,最近受过PHP代码审查的任务。 While going through the PHP source code, I'v noticed that a variable is initialised in an if, while, switch and do statement then same variable is used outside these statements. 在浏览PHP源代码时,我注意到一个变量在if,while,switch和do语句中初始化,然后在这些语句之外使用相同的变量。 Below is a fragment the code 下面是片段代码

Senario 1 Senario 1

if ($status == 200) {
     $messageCode = "SC001";
}

// Here, use the $message variable that is declared in an if
$queryDb->selectStatusCode($message);

Senario 2 Senario 2

foreach ($value->children() as $k => $v) {
    if ($k == "status") {
        $messageCode = $v;
    }
}

// Here, use the $messageCode variable that is declared in an foreach
$messageCode ....

In my understanding, a variable declared in a control statement is only accessible with in the control code block. 据我了解,在控制语句中声明的变量只能通过控制代码块访问。

My question is, what is the variable scope of a variable in a PHP function and how is this variable accessible outside a control statement block? 我的问题是,PHP函数中变量的变量作用域是什么?如何在控制语句块外部访问此变量?

How is that above code working and producing expected results? 上面的代码如何工作并产生预期的结果?

In PHP control statements have no separate scope. 在PHP中,控制语句没有单独的范围。 They share the scope with the outer function or the global scope if no function is present. 它们与外部功能或全局范围共享作用域(如果不存在任何功能)。 ( PHP: Variable scope ). PHP:可变范围 )。

$foo = 'bar';

function foobar() {
    $foo = 'baz';

    // will output 'baz'
    echo $foo;
}

// will output 'bar'
echo $foo;

Your variables will have the last value assigned within the control structure. 您的变量将在控制结构中分配有最后一个值。 It is good practice to initialize the variable before the control structure but it is not required. 优良作法是在控制结构之前初始化变量,但这不是必需的。

// it is good practice to declare the variable before
// to avoid undefined variables. but it is not required.
$foo = 'bar';
if (true == false) {
    $foo = 'baz';
}

// do something with $foo here

Namespaces do not affect variable scope. 命名空间不影响变量范围。 They only affect classes, interfaces, functions and constants ( PHP: Namespaces Overview ). 它们仅影响类,接口,函数和常量( PHP:命名空间概述 )。 The following code will output 'baz': 以下代码将输出“ baz”:

namespace A { 
    $foo = 'bar';
}

namespace B {
    // namespace does not affect variables
    // so previous value is overwritten
    $foo = 'baz';
}

namespace {
    // prints 'baz'
    echo $foo;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM