情况:我们有一小段 PHP 代码检查变量是否具有特定值,但由于数组索引及其值根本没有设置,这将产生 E_NOTICE 错误:
这会触发通知
<?php
$arr = array();
if ($arr['name']=='john') {
echo('This should not work');
} else {
echo('In your computer, ignoring your notice');
}
这引发了一个很好的通知:
PHP Notice: Undefined index: name in /home/hvanmegen/test.php on line 5
PHP Stack trace:
PHP 1. {main}() /home/hvanmegen/test.php:0
现在请向我解释一下,如果该值检查抛出错误,下面打印的代码如何在不抛出相同异常的情况下正常工作?!?!
这不会触发通知!
<?php
$arr = array();
if (isset($arr['name']) && $arr['name']=='john') {
echo('This should not work');
} else {
echo('In your computer, ignoring your notice');
}
输出:
In your computer, ignoring your notice
AND 检查是否会在返回第一个 false 时立即中止/丢弃?
只要比较列表中的第一个 false 被触发,PHP 是否只是跳过第二次检查而从未实际执行第二次检查?
此外,将两个 if 语句分开是否被认为是良好的编码习惯,还是我在这里的编码有点太过时了?人们会认为检查这一点的正确方法是这样的:
<?php
$arr = array();
if (isset($arr['name'])) {
if ($arr['name']=='john') {
echo('Hi john');
} else {
echo('Hi not-john, where is john?');
}
} else {
echo('I cannot check what I do not have');
}
输出:
I cannot check what I do not have
是我的强制症想要将“isset()”放在其他语句之外,还是我的方法完全多余和过时了?还是我坚持这样的想法,即您应该尽可能多地使用“通用语言”(使用与语言无关的语法,以便尽可能容易地从一种语言切换到另一种语言)编写代码?
其他编程和脚本语言(Java、C++/C#、Javascript、Python)如何处理这个问题?
最佳答案
Does PHP just skip the second check and never actually perform the second check whenever the first false is triggered in a list of comparisons??
是的。它叫做short-circuit evaluation .
&&
(和)如果左侧为假,则不会计算右侧,因为结果必须为假。
||
(或)如果左侧为真,则不计算右侧,因为结果必须为真。
Also, is it considered good coding practice to separate the two if statements or am I being a bit too old fashioned with my coding here?
虽然编码风格非常个人化,但是一旦您理解了短路评估,就没有必要将它们分开。我相信在这种情况下,大多数程序员会将条件保留在一个 if
中,特别是因为它们密切相关并且基本上是检查同一事物的两个步骤。
How do other programming and scripting languages (Java, C++/C#, JavaScript, Python) handle this?
与 PHP 相同。
关于php - 如果我将 isset() 放在同一个 IF 语句中,为什么我没有收到 PHP 通知数组索引不存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24061642/