【问题标题】:list(), if and short-circuit evaluationlist(), if 和短路评估
【发布时间】:2012-12-16 09:32:17
【问题描述】:

我有以下代码片段:

$active_from = '31-12-2009';
if(list($day, $month, $year) = explode('-', $active_from) 
    && !checkdate($month, $day, $year)) {
    echo 'test';
}

为什么会出现未定义变量错误?

list($day, $month, $year) = explode('-', $active_from) 返回true,所以list() 被评估,不是吗?我想,应该定义变量吗?我要监督什么?

这在我看来是一样的并且不会引发错误:

$active_from = '31-12-2009';
list($day, $month, $year) = explode('-', $active_from);
if(checkdate($month, $day, $year)) {
    echo 'test';
}

这不会引发错误:

if((list($day, $month, $year) = explode('-', $active_from)) && checkdate($month, $day, $year)) {

但我真的不明白为什么:-)

感谢解释

【问题讨论】:

标签: php if-statement short-circuiting


【解决方案1】:

这是operator precedence 的问题,在您的情况下,&&= 之前评估,导致您描述的错误。

您可以通过将赋值语句放在括号内来解决此问题。

明确地,你的代码应该是这样的

if(  (list($day, $month, $year) = explode('-', $active_from))
     && !checkdate($month, $day, $year)) {

请注意,我已将其从 if( $a=$b && $c ) 更改为 if( ($a=$b) && $c )。括号强制赋值运算符 (=) 在连词 (&&) 之前进行计算,这正是您想要的。

【讨论】:

  • 没问题,@FabianBlechschmidt。 (和新年快乐;-))
【解决方案2】:

了解operator precedence

if ( list($day, $month, $year) = explode('-', $active_from) && !checkdate($month, $day, $year) ) {

等同于

if ( list($day, $month, $year) = (explode('-', $active_from) && !checkdate($month, $day, $year)) ) {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-26
    • 2015-11-14
    • 2017-01-21
    • 2012-02-10
    • 2010-12-21
    • 1970-01-01
    • 2013-06-19
    相关资源
    最近更新 更多