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

Ternary operator not working if I am using echo

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

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

怎么样

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

您应该改为阅读 the difference between print and echo in PHP in general. Tl;dr use 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.';