php 中的一行 if 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21078149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
one line if statement in php
提问by andrew
I'd like to to some thing similar to javascripts
我想要一些类似于 javascripts 的东西
var foo = true;
foo && doSometing();
but this doesnt seem to work in php.
但这似乎在 php 中不起作用。
I'm trying to add a class to a label if a condition is met and I'd prefer to keep the embedded php down do a minimum for the sake of readability.
如果满足条件,我正在尝试向标签添加一个类,并且为了可读性,我更愿意将嵌入式 php 保持在最低限度。
so far I've got:
到目前为止我有:
<?php $redText='redtext ';?>
<label class="<?php if ($requestVars->_name=='')echo $redText;?>labellong">_name*</label>
<input name="_name" value="<?php echo $requestVars->_name; ?>"/>
but even then the ide is complaining that I have an if statement with out braces.
但即便如此,ide 还是抱怨我有一个没有大括号的 if 语句。
回答by sanjeev
use the ternary operator ?:
使用三元运算符 ?:
change this
改变这个
<?php if ($requestVars->_name=='')echo $redText;?>
with
和
<?php echo ($requestVars->_name=='')?$redText:'';?>
In short
简而言之
// (Condition)?(thing's to do if condition true):(thing's to do if condition false);
回答by Muhammad Adeel Malik
You can use Ternary operator logicTernary operator logic is the process of using "(condition)? (true return value) : (false return value)" statements to shorten your if/else structures. i.e
您可以使用三元运算符逻辑三元运算符逻辑是使用“(条件)?(真返回值):(假返回值)”语句来缩短 if/else 结构的过程。IE
/* most basic usage */
$var = 5;
$var_is_greater_than_two = ($var > 2 ? true : false); // returns true
回答by ceuben
Something like this?
像这样的东西?
($var > 2 ? echo "greater" : echo "smaller")
回答by Boris
The provided answers are the best solution in your case, and they are what I do as well, but if your text is printed by a function or class method you could do the same as in Javascript as well
提供的答案是您的最佳解决方案,它们也是我所做的,但是如果您的文本是通过函数或类方法打印的,您也可以像在 Javascript 中那样做
function hello(){
echo 'HELLO';
}
$print = true;
$print && hello();

