[英]Is there a more elegant way to write this code?
<?php if (!empty($box1) && !empty($box2)) { echo ' | content here'; } ?>
<?php if (!empty($box1) && empty($box2)) { echo 'content here'; } ?>
基本上,如果box2为空,我想摆脱管道。 有没有更好的方法来写这个?
<?php if (!empty($box1)) { echo (empty($box2) ? '' : ' | ') . 'content here'; } ?>
很难说在没有更宏大的计划的情况下优雅地编写它的“最佳”方法是什么,但是至少您可以将其缩短如下:
<?php if(!empty($box1)) { echo (!empty($box2) && ' |') . 'content here'; } ?>
或者,如果您不喜欢&&
样式,则可以使用三元运算符:
<?php if(!empty($box1)) { echo (!empty($box2) ? ' |' : '') . 'content here'; } ?>
或其他有条件的。
粗略地说,如果“最”优雅的方法是仔细看一下$box1
和$box2
代表什么,然后按照以下方式创建视图帮助器(在MVC方法中):
class SomeModel {
int $box1;
int $box2;
function make_suffix() {
$suffix = '';
if(!empty($this->box1)) {
if(!empty($this->box2)) {
$suffix .= ' | ';
}
$suffix .= 'content here';
}
return $suffix;
}
}
<?php
if (!empty(&box1)) {
if (!empty($box2) {
echo ' | ';
}
echo 'content here';
}
?>
仅使用三元运算符 :
<?php echo !empty($box1) ? ( !empty($box2) ? ' | ' : '' ) . 'content here' : '' ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.