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 语句变量范围


基础教程推荐
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 在多维数组中查找最大值 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01