【问题标题】:eval error when using "if" short form使用“if”短格式时出现评估错误
【发布时间】:2013-02-10 22:07:36
【问题描述】:

当做类似的事情时

$date = mktime();
$xxx = 'if ( date("N",$date ) == 1 ) { return TRUE; } else { return FALSE; }';
$yyy = eval( $xxx );
echo $yyy;

它有效。

但是当做类似的事情时

$date = mktime();
$xxx = '( date("N",$date) == 1 ? return TRUE : return FALSE );';
$yyy = eval( $xxx );
echo $yyy;

我收到类似的错误

解析错误:语法错误,/my_path/my_file.php(107) 中出现意外的 T_RETURN:第 1 行的 eval() 代码

为什么?

【问题讨论】:

    标签: php eval parse-error


    【解决方案1】:

    这和eval一点关系都没有。

    让我们创建 real 测试用例:

    <?php
    function foo()
    {
       $date = mktime();
       ( date("N",$date) == 1 ? return TRUE : return FALSE );
    }
    
    foo();
    ?>
    

    Output:

    Parse error: syntax error, unexpected T_RETURN on line 5
    

    return 是一个语句,而不是一个表达式,所以你不能将它嵌套到一个你想要在这里做的表达式中。条件运算符不是if/else 的单行替换。

    正确使用条件运算符:

    return (date("N",$date) == 1 ? TRUE : FALSE);
    

    简化为:

    return (date("N",$date) == 1);
    

    在您的代码中,如下所示:

    $date = mktime();
    $xxx = 'return (date("N",$date) == 1);';
    $yyy = eval($xxx);
    echo $yyy;
    

    【讨论】:

      【解决方案2】:

      我很确定应该是这样的

      $xxx = 'return ( date("N",$date) == 1 ? TRUE : FALSE );';
      

      三元运算符生成的东西是值(表达式)而不是命令。

      【讨论】:

      • 谢谢,有时我看不到森林,因为所有的树;-)
      猜你喜欢
      • 1970-01-01
      • 2019-07-25
      • 1970-01-01
      • 2015-05-11
      • 2012-12-16
      • 2016-10-28
      • 2011-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多