Php 有没有更优雅的方法来编写这段代码?
基本上,如果box2是空的,我想去掉管道。有没有更好的方法来写这个?Php 有没有更优雅的方法来编写这段代码?,php,Php,基本上,如果box2是空的,我想去掉管道。有没有更好的方法来写这个? <?php if (!empty($box1) && !empty($box2)) { echo ' | content here'; } ?> <?php if (!empty($box1) && empty($box2)) { echo 'content here'; } ?> 如果没有更宏大的方案,很难说写得优雅的“最佳”方式是什么,但至少你可以将其缩短如下:
<?php if (!empty($box1) && !empty($box2)) { echo ' | content here'; } ?>
<?php if (!empty($box1) && empty($box2)) { echo 'content here'; } ?>
如果没有更宏大的方案,很难说写得优雅的“最佳”方式是什么,但至少你可以将其缩短如下:
<?php if (!empty($box1)) { echo (empty($box2) ? '' : ' | ') . 'content here'; } ?>
或者其他条件
粗略地说,如果“最”优雅的方式是仔细查看$box1
和$box2
所代表的内容,然后创建一个视图辅助对象(在MVC方法中),如下所示:
<?php if(!empty($box1)) { echo (!empty($box2) ? ' |' : '') . 'content here'; } ?>
只需使用:
谢谢。只是个附带问题。($box2)旁边的问号是什么?它是三元运算符。基本上,(A?B:C)
运行A,将结果解释为二进制。如果结果为真,则计算B。否则,计算C。例如,echo($x==1?'x=1':'x!=1')如果$x为1,代码>将打印“x=1”。如果$x不是1,那么将打印“x!=1”谢谢你@Steven Xu和@Foo Bah。
<?php if(!empty($box1)) { echo (!empty($box2) ? ' |' : '') . 'content here'; } ?>
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' : '' ?>