shorthand 的感叹?标记运算符

shorthand if explanation ? mark operator

对于模板引擎,我想使用 shorthand if 条件。 我需要检查一个值是否为 != null 如果为真,则打印出一些行。 我尝试了什么:

echo "test" ($user->affiliate_id !=null) ?   

我不知道在?后面写什么。

语法应该是这样的

echo (condition) ? write if true code part here : write else part here

这意味着在你的情况下它会像

echo ($user->affiliate_id !=null) ? 'test' : 'not null'

试试这个:

echo ($user->affiliate_id != null )?"test":"";

正如@Federinco 所提到的,它被称为三元运算符,官方文档在这里:http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary

三元运算符的工作原理如下:

condition ? true branch : false branch

例如:

$cost = isset($discount) ? $total - $discount : $total;

在上面的示例中,我们检查是否设置了折扣,如果设置了,我们从当前总额中删除折扣,如果没有,我们就将成本设置为总额。

您还可以像这样使用三元运算符做其他很酷的事情:

$name = $username ?: 'Guest';

在上面的代码中我们正在检查 $username 是否存在,如果存在我们将 $name 设置为 $username 否则我们将 $name 设置为 Guest

请注意,如果滥用三元运算符,可能会导致可读性问题,因此在使用它的地方要小心,如果不是三元运算符,则不要牺牲标准条件语句的额外行将清楚它在做什么。

你要的是ternary operator

您的代码应如下所示

echo "test" . (($user->affiliate_id !=null) ? 'stringToOutput ifNotNull' : 'stringToOutput if is null');

此外,PHP 7 引入了您可以使用的 Null coalescing operator。你可以这样做

echo 'test' . ($user->affiliate_id ?? 'ID not found!');

在这种情况下,如果设置了 $user->affiliate_id 且不为空,它将被打印 而不是 'ID not found!' 消息

$someVariable = $condition ? $valueA : $valueB等同于:

if ( $condition ) {
    $someVariable = $valueA;
}
else {
    $someVariable = $valueB;
}

所以,基本上,如果条件是 TRUE$someVariable 将取 ? 符号后的第一个值。如果FALSE,它将取第二个值(:符号之后的值)。

有一种特殊情况,您可以定义第一个值,它是这样的:$someVariable = $someValue ?: $someOtherValue。相当于:

if ( $someValue ) {
    $someVariable = $someValue;
}
else {
    $someVariable = $someOtherValue;
}

因此,如果 $someValue 计算为 TRUE(任何不同于 0 的值都计算为 TRUE),那么 $someVariable 将捕获该值.否则,它会捕获 $someOtherValue.

举个例子:

function printGender( $gender ) {
    echo "The user's gender is: " . ( $gender == 0 ? "Male" : "Female" );
}

printGender(0); // Will print "The user's gender is: Male"
printGender(1); // Will print "The user's gender is: Female"

另一个例子:

function printValuesStrictlyDifferentThanZero( $value ) {
    echo "Value: " . ( $value ?: 1 );
}

printValuesStrictlyDifferentThanZero(0); // $value evaluates to FALSE, so it echoes 1
printValuesStrictlyDifferentThanZero(1); // $value evaluates to TRUE, so it echoes that $value

编辑:

运算符 ?: NOT 称为 ternary operator。有多种方法可以定义三元运算符(采用三个操作数的运算符)。它是一个三元运算符,但不是三元运算符。有些人只是将其称为三元运算符,因为他们已经习惯这样做,并且可能是 PHP 中唯一广为人知的三元运算符,但三元运算符比这更通用。

它的名字是条件运算符,或者更严格地说,三元条件运算符

假设我定义了一个名为 log base 的新运算符,如果以 $C 为底的数字 $A 的对数等于 $B,则内联计算它的语法像 $correct = $A log $B base $C 和它 returns TRUE 如果对数是正确的,或者 FALSE 如果它不是。

当然这个操作是假设的,但它一个三元运算符,就像?:一样。我将其称为 对数检查器运算符