PHP 变量生命周期/范围

PHP variable life cycle/ scope

我是一名 Java 开发人员,最近我的任务是 PHP 代码审查。在查看 PHP 源代码时,我注意到在 if、while、switch 和 do 语句中初始化了一个变量,然后在这些语句之外使用了相同的变量。下面是一段代码

塞纳里奥 1

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

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

塞纳里奥 2

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

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

据我了解,在控制语句中声明的变量只能在控制代码块中访问。

我的问题是, PHP 函数中变量的变量范围是什么?如何在控制语句块外访问该变量?

上述代码如何工作并产生预期结果?

在 PHP 中,控制语句没有单独的作用域。如果不存在函数,它们与外部函数或全局范围共享范围。 (PHP: Variable scope).

$foo = 'bar';

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

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

// will output 'bar'
echo $foo;

您的变量将具有在控制结构中分配的最后一个值。在控制结构之前初始化变量是一种很好的做法,但这不是必需的。

// 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

命名空间不影响变量作用域。它们只影响 类、接口、函数和常量 (PHP: Namespaces Overview)。下面的代码会输出'baz':

namespace A { 
    $foo = 'bar';
}

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

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