PHP变量生命周期/范围


PHP variable life cycle/ scope

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

Senario 1

if ($status == 200) {
     $messageCode = "SC001";
}
// Here, use the $message variable that is declared in an if
$queryDb->selectStatusCode($message);

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

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

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

上面的代码是如何工作并产生预期结果的?

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

$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;
}