PHP变量生命周期/范围

时间:2015-11-17 07:00:01

标签: php variables scope lifecycle

我是一名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函数中变量的变量范围,以及如何在控制语句块外部访问此变量?

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

1 个答案:

答案 0 :(得分:5)

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