开发者

PHP question mark

$hideCode = $likes开发者_JAVA百科Obj->isAlreadyLikedByUser(facebookUID()) ? 'style="display:none;"' : '';

Can anyone explain to me what that question mark does in this line of code? Thanks a lot!


This is called the Ternary Operator, and it's common to several languages, including PHP, Javascript, Python, Ruby...

$x = $condition ? $trueVal : $falseVal;

// same as:

if ($condition) {
    $x = $trueVal;
} else {
    $x = $falseVal;
}

One very important point to note, when using a ternary in PHP is this:

Note: Please note that the ternary operator is a statement, and that it doesn't evaluate to a variable, but to the result of a statement. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions. source


Actually this statment is representing a Ternary operation, a conditional expression:

// works like:    (condition) ? if-true : if-false;

$hideCode = $likesObj->isAlreadyLikedByUser(facebookUID()) ?  'style="display:none;"':'';

in your case $hideCode will have style="display:none;" value if

$likesObj->isAlreadyLikedByUser(facebookUID())

will return true, else it will be null or empty.


It's a shorter version of a IF statement.

$hideCode = $likesObj->isAlreadyLikedByUser(facebookUID()) ? ' style="display:none;"':'';

if in fact :

if($likesObj->isAlreadyLikedByUser(facebookUID()))
{
   $hideCode = 'style="display:none"';
}
else
{
 $hideCode = "";
}

For the purism :

It's representing a Ternary operation


This is the simple if-then-else type logic:

(condition) ? (if-true-value) : (if-false-value)

so in your case, the condition is checked (i.e. has the page already been liked by the user); if yes (true condition), then style="display:none;" is printed so that whatever the element you're using is not displayed. Otherwise, an empty string is printed, which is the equivalent of not printing anything at all, naturally.


It is the ternary operator: it means

if $likesObj->isAlreadyLikedByUser(facebookUID()) is true assign style="display:none; to the variable, otherwise assign ''


It's part of a ternary operator. The first part is the conditional of an if-else statement. After the question mark is the "if" block, and after the colon is the "else" block.


$hideCode = $likesObj->isAlreadyLikedByUser(facebookUID()) ? 'style="display:none;"':'';

This is the same as the following:

if ($likesObj->isAlreadyLikedByUser(facebookUID()))
{
    $hideCode = 'style="display:none;"';
}
else
{
    $hideCode = '';
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜