【问题标题】:Ternary operator not working if I am using echo如果我使用回声,三元运算符不起作用
【发布时间】:2019-02-28 08:32:13
【问题描述】:

我正在使用这个三元运算符:

$this->checkIfProductCategoriesContainsString($productId, $categoryNeedle) !== false ? echo "Category containing categoryNeedle exists" : echo "Category does not exist.";

我也试过这样:

($this->checkIfProductCategoriesContainsString($productId, $categoryNeedle) !== false) ? echo "Category containing categoryNeedle exists" : echo "Category does not exist.";

但我的 IDE 显示 unexpected echo after ?

【问题讨论】:

  • 语言?三元运算符通常适用于无法计算的表达式:cond ? trueValue : falseVaue,而不是cond ? doIfTrue : doIfFalse。 echo 函数有返回值吗?
  • 那么echo不会返回任何东西,你不能这样用但是你可以用if else代替

标签: php ternary-operator


【解决方案1】:

怎么样

echo(
    $this->checkIfProductCategoriesContainsString($productId, $categoryNeedle) !== false
        ? "Category containing categoryNeedle exists"
        : "Category does not exist."
);

【讨论】:

    【解决方案2】:

    一般来说,您应该阅读 PHP 中 printecho 之间的 the difference。 Tl;博士改用print

    $this->checkIfProductCategoriesContainsString($productId, $categoryNeedle) ?
        print "Category containing category needle exists" : 
        print "Category does not exist.";
    

    但最好是:

    echo $this->checkIfProductCategoriesContainsString($productId, $categoryNeedle) ?
        'Category containing category needle exists' : 
        'Category does not exist.';
    

    【讨论】:

      猜你喜欢
      • 2016-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      • 2019-11-14
      • 2021-01-14
      • 2011-08-30
      相关资源
      最近更新 更多