这个赋值结构叫什么?你可以在Php中做吗? [英] What is this assignment construct called? And can you do it in Php?

查看:115
本文介绍了这个赋值结构叫什么?你可以在Php中做吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常在Javascript中使用以下构造:

  var foo = other_var || 默认值; 

在Javascript中,如果左侧是伪造的,则右侧的值被分配。 / p>

它非常方便,并且可以节省更长时间和不必要的显式三进制表达式。



是否有这个名称一种构造?



奖金:在Php中没有使用三元运算符的方法吗?



PS:另一个变体是如果你没有得到一个真实的值而不是给出一个默认值,那就是抛出一个错误:

  var foo = something || alert(foo not set!); 


解决方案

逻辑或(通常

在某些(如 C,C ++ )中,它的运算符在许多语言中是非常不同的如下所示:评估左边;如果是真的,返回true,否则评估右侧,否则返回true,否则返回true。结果总是在这里布尔值。



在其他(如 Javascript,Python )中,我相信PHP也更像:评估左侧;如果它是真的,返回它,否则评估右边并返回结果。然后,结果可以是任何类型,你可以像这样的结构:



a =(b || c); //等同于a = b? b:c;



或非常喜欢:

  function compare(A,B){//如果A  B 
返回Bx - Ax || B.y - A.y;
}


I have often used the following construct in Javascript:

var foo = other_var || "default_value";

In Javascript, if the left side is falsy, then the value on the right side is assigned.

It is very handy, and saves writing longer and unnecessarily explicit ternary expressions.

Is there a name for this sort of construct ?

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

PS: another variant is to throw an error if you don't get a truthy value, instead of giving a default value:

var foo = something || alert("foo is not set!");

解决方案

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;
}

这篇关于这个赋值结构叫什么?你可以在Php中做吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆