Sim*_*ele 2 php variables lifecycle 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);
Run Code Online (Sandbox Code Playgroud)
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 ....
Run Code Online (Sandbox Code Playgroud)
根据我的理解,控制语句中声明的变量只能在控制代码块中访问.
我的问题是,PHP函数中变量的变量范围是什么?如何在控制语句块之外访问此变量?
上面的代码如何工作并产生预期的结果?
在PHP中,控制语句没有单独的范围.如果不存在函数,它们与外部函数或全局范围共享范围.(PHP:可变范围).
$foo = 'bar';
function foobar() {
$foo = 'baz';
// will output 'baz'
echo $foo;
}
// will output 'bar'
echo $foo;
Run Code Online (Sandbox Code Playgroud)
您的变量将在控制结构中分配最后一个值.最好在控制结构之前初始化变量,但这不是必需的.
// 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
Run Code Online (Sandbox Code Playgroud)
命名空间不会影响变量范围.它们只影响类,接口,函数和常量(PHP:命名空间概述).以下代码将输出'baz':
namespace A {
$foo = 'bar';
}
namespace B {
// namespace does not affect variables
// so previous value is overwritten
$foo = 'baz';
}
namespace {
// prints 'baz'
echo $foo;
}
Run Code Online (Sandbox Code Playgroud)