简体   繁体   English

PHP三元运算符多个语句

[英]PHP Ternary Operator multiple statements

Hello so I have a piece of code: 您好,我有一段代码:

if($request['txt_!'] != "") {
  $randl1_1 = mt_rand(100000, 999999);
} else {
  $randl1_1 = '';
}

And when I convert it to a ternary operator: 当我将其转换为三元运算符时:

$randl1_1 = ($request['txt_1'] != "") ? mt_rand(100000, 999999) : '';

What if I will add some in my if? 如果我在if中添加一些内容怎么办? Like, 喜欢,

if($request['txt_!'] != "") {
  $randl1_1 = mt_rand(100000, 999999);
  someFunction();
} else {
  $randl1_1 = '';
}

Is it possible in a ternary operator? 是否有可能在三元运算符中?

It's possible, but it would make the use of a ternary less useful as it would clutter it (especially if you wanted to keep it on a single line). 这是可能的,但它会使三元组的使用变得不那么有用,因为它会使它变得杂乱(特别是如果你想把它保持在一条线上)。 If you had it in the expression as the RHS, its return value would also be assigned to $randl1_1 . 如果您在表达式中将其作为RHS使用,则其返回值也将分配给$randl1_1

If someFunction() returned something truthy, then... 如果someFunction()返回了一些真实的东西,那么......

$randl1_1 = ($request['txt_1'] != "") ? someFunction() && mt_rand(100000, 999999) : '';

If it didn't you could use || 如果没有,你可以使用|| . But as you can see, this is ugly. 但正如你所看到的,这很难看。 If someFunction() relies on $randl1_1 , well, then you have worse problems. 如果someFunction()依赖于$randl1_1 ,那么你就会遇到更糟糕的问题。 :) :)

In your second case, I would use the more verbose example that you cited. 在你的第二种情况下,我会使用你引用的更详细的例子。 You want your code to communicate to yourself and others clearly its intent. 您希望您的代码能够清楚地表达自己和他人的意图。

Trying to shoehorn everything into a ternary is a bad practice. 试图把所有东西都塞进一个三元组是一种不好的做法。

You can't put multiple statements into the parameters of the ternary operator. 您不能将多个语句放入三元运算符的参数中。 You can use the comma operator to evaluate multiple expressions, though: 但是,您可以使用逗号运算符来计算多个表达式:

$rand1_1 = ($request['txt_1'] != "") ? (someFunction(), mt_rand(100000, 999999)) : '';

However, the comma operator returns its last operand. 但是,逗号运算符返回其最后一个操作数。 If you want to execute something after computing the value you want to assign, it won't work, eg 如果要计算要分配的值执行某些操作,则无法执行此操作,例如

$rand1_1 = ($request['txt_1'] != "") ? (mt_rand(100000, 999999), someFunction()) : '';

This will set $rand1_1 to the value returned by someFunction() , not the random value. 这会将$rand1_1设置$rand1_1 someFunction()返回的值,而不是随机值。 You'd have to save the random value in a variable: 您必须将随机值保存在变量中:

$rand1_1 = ($request['txt_1'] != "") ? ($temp = mt_rand(100000, 999999), someFunction(), $temp) : '';

All this extra clutter makes the ternary really hard to read, negating the value of using it instead of a regular if statement. 所有这些额外的混乱使得三元组真的难以阅读,否定了使用它而不是常规if语句的价值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM