如果我使用echo,三元运算符不起作用

时间:2019-02-28 08:32:14

标签: php ternary-operator

我正在使用此三元运算符:

$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 ?

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

一般而言,您应该在printecho之间阅读有关the difference的内容。 Tl; dr改用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.';