PHP switch statement variable scope(PHP switch 语句变量范围)
问题描述
在 PHP 中,switch 语句中的变量作用域是如何处理的?
In PHP, how is variable scope handled in switch statements?
例如,举个假设的例子:
For instance, take this hypothetical example:
$someVariable = 0;
switch($something) {
case 1:
$someVariable = 1;
break;
case 2:
$someVariable = 2;
break;
}
echo $someVariable;
这会打印 0 还是 1/2?
Would this print 0 or 1/2?
推荐答案
你的整个代码部分中的变量将是相同的:在 PHP 中没有每个块"的变量范围.
The variable will be the same in your whole portion of code : there is not variable scope "per block" in PHP.
所以,如果 $something
是 1
或 2
,那么你输入的 case
之一switch
,您的代码将输出 1 或 2.
So, if $something
is 1
or 2
, so you enter in one of the case
of the switch
, your code would output 1 or 2.
另一方面,如果 $something
不是 1
也不是 2
(例如,如果它被视为 0
,您发布的代码就是这种情况,因为它没有初始化为任何东西),您将不会进入任何 case
块;并且代码将输出 0
.
On the other hand, if $something
is not 1
nor 2
(for instance, if it's considered as 0
, which is the case with the code you posted, as it's not initialized to anything), you will not enter in any of the case
block ; and the code will output 0
.
这篇关于PHP switch 语句变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP switch 语句变量范围


基础教程推荐
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何替换eregi() 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01