What is this assignment construct called? And can you do it in Php?

瘦欲@ 提交于 2019-12-04 14:00:19

The logical-or (usually ||) operator is drastically different in many languages.

In some (like C, C++) it works like: "Evaluate the left-hand side; if it's true, return true, otherwise evaluate the right hand-side and return true if it's true or false otherwise." The result is always boolean here.

In others (like Javascript, Python, I believe that PHP also) it's more like: "Evaluate the left-hand side; if it's true, return it, otherwise evaluate the right-hand side and return the result." Then the result can be of any type and you can do constructs like:

a = (b || c); // equivalent to a = b ? b : c;

or quite fancy:

function compare(A, B) { // -1 if A<B, 0 if A==B, 1 if A>B
    return B.x - A.x || B.y - A.y;
}

I believe it's just called an OR construct. There are a lot of good examples on using assignments here: http://php.net/manual/en/language.operators.assignment.php

It is just a logical OR operator. Follow the link for more information in javascript.

From the examples in the docs:

o1=true || true       // t || t returns true
o2=false || true      // f || t returns true
o3=true || false      // t || f returns true
o4=false || (3 == 4)  // f || f returns false
o5="Cat" || "Dog"     // t || t returns Cat
o6=false || "Cat"     // f || t returns Cat
o7="Cat" || false     // t || f returns Cat

EDIT: Regarding the BONUS, it appears as though you can do something similar with the ternary in recent versions of PHP by doing:

expr1 ?: expr3

From the PHP docs:

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

I'm not familiar with PHP, so I'd be interested to know the result.

This works:

$mytruevalue = true;
$foo = $mytruevalue or $foo = "20";
echo $foo;

The above prints "1" because that is the string representation of true ($mytruevalue is true).

$myfalsevalue = false;
$foo = $myfalsevalue or $foo = "20";
echo $foo;

This, however, prints "20" because $myfalsevalue is false.

If both values are equal to false, it prints nothing.

Hope this helps.

Is there a name for this sort of construct ?

It is the logical OR operator.

Bonus: Is there a trick to do this in Php without using a ternary operator?

No, with PHP, you can do so only with the help of ternay operator.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!