一行if语句在PHP中 [英] One line if statement in PHP

查看:60
本文介绍了一行if语句在PHP中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一些类似于JavaScript的事情

I'd like to to some thing similar to JavaScript's

var foo = true;
foo && doSometing();

但这在PHP中似乎不起作用.

but this doesn't 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 to a minimum for the sake of readability.

到目前为止,我已经得到:

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; ?>"/>

但即使那样,IDE仍在抱怨我有一个不带花括号的if语句.

but even then the IDE is complaining that I have an if statement without braces.

推荐答案

使用三元运算符?:

更改此

<?php if ($requestVars->_name == '') echo $redText; ?>

使用

<?php echo ($requestVars->_name == '') ? $redText : ''; ?>

简而言之

// (Condition)?(thing's to do if condition true):(thing's to do if condition false);

这篇关于一行if语句在PHP中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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