【问题标题】:php if else multiple lines shorthandphp if else 多行速记
【发布时间】:2016-12-26 17:12:25
【问题描述】:

我想有条件地执行两个函数:

while($row = mysql_fetch_assoc($result))
    (strtolower($message) == $row['question'])
        ? msg($row['answer']) && update($row['question'])
        : '';

但此代码不起作用。

【问题讨论】:

  • 什么不起作用?如果 msg() 返回 false,update() 当然不会触发。
  • msg()和update()的定义是什么?这些可能会导致问题。既然你说if(strtolower($message) == $row['question']) { msg($row['answer']) && update($row['question'])} else { return ''}
  • 语法正确,没有错误。函数 msg();和更新();只是mysql_update。此代码没有 update();功能正常工作。当它们是两个功能时,第二个功能不起作用。
  • 尝试|| 而不是&&
  • 就像@Bert 所说,update() 函数不会触发,因为您使用的是三元运算符,而三元运算符只使用简单的输入。您唯一能做的就是编写另一个函数,可能是 msg_upate(),用它们的参数包装 msg()update(),并将语句更改为:(strtolower($message) == $row['question']) ? msg_update($row['answer']) : '';

标签: php if-statement conditional-operator shorthand


【解决方案1】:

简写仅适用于单行语句。由于您的 if 语句包含两行,因此速记不起作用。通常 while 循环的格式如下:

while (/* condition */)
{
    // code to be executed
}

你的三元表达式也不正确;应该写成这样:

(/* condition */) ? /* if true do this */ : /* if false do this */

在三元语句的第二部分 (?:),您使用条件运算符 &&,它比较两个布尔表达式。据我了解,您使用&& 的意图是执行两行,这是不正确的。参考文档:PHP Docs (Comparison operators)

你需要用大括号编写while循环,因为你的if语句包含多行代码,如下:

while($row = mysql_fetch_assoc($result))
{ 
    if (strtolower($message) == $row['question'])
    {
        msg($row['answer']);
        update($row['question']);
    }
}

【讨论】:

    【解决方案2】:

    定义一个函数msg_update() 包装msg()update()

    function msg_update($row) {
        msg($row);
        update($row);
    }
    

    那么你可以这样做:

    while($row = mysql_fetch_assoc($result)) (strtolower($message) == $row['question']) ? msg_update($row['answer']) : '';
    

    这是因为三元运算符只需要简单的操作。希望对你有用。

    【讨论】:

      【解决方案3】:

      您是否有任何理由需要使用速记代码来执行此操作?

      以下内容将更具可读性,并且当您(或其他人)将来某个时候更新/更改/审查/调试代码时,预期的结果将更加明显。

      while($row = mysql_fetch_assoc($result)) {
          if (strtolower($message) == $row['question']) {
              msg($row['answer']);
              update($row['question']);
          }
      }
      

      通常缩短的 ?: 版本仅用于最简单的条件和操作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-08
        • 2016-10-06
        • 2011-07-17
        • 2016-05-15
        • 2013-04-08
        • 2013-07-18
        • 2014-12-05
        • 2013-08-30
        相关资源
        最近更新 更多