是否有更优雅的方式来编写此代码?

时间:2011-02-12 04:09:57

标签: php

<?php if (!empty($box1) && !empty($box2)) { echo ' | content here'; } ?>

<?php if (!empty($box1) && empty($box2)) { echo 'content here'; } ?>

基本上,如果box2为空,我想摆脱管道。有没有更好的方法来写这个?

4 个答案:

答案 0 :(得分:0)

<?php if (!empty($box1)) { echo (empty($box2) ? '' : ' | ') . 'content here'; } ?>

答案 1 :(得分:0)

很难说没有更宏大的方案,优雅地写出它的“最佳”方式是什么,但至少你可以按如下方式缩短它:

<?php if(!empty($box1)) { echo (!empty($box2) && ' |') . 'content here'; } ?>

或者,如果您不喜欢&&样式,则可以使用三元运算符:

<?php if(!empty($box1)) { echo (!empty($box2) ? ' |' : '') . 'content here'; } ?>

或另一个条件。

粗略地说,如果“最”优雅的方式是仔细查看$box1$box2代表什么,然后创建一个视图助手(在MVC方法中):< / p>

class SomeModel {
  int $box1;
  int $box2;
  function make_suffix() {
    $suffix = '';
    if(!empty($this->box1)) {
      if(!empty($this->box2)) {
        $suffix .= ' | ';
      }
      $suffix .= 'content here'; 
    }
    return $suffix;
  }
}

答案 2 :(得分:0)

<?php
if (!empty(&box1)) {
  if (!empty($box2) {
    echo ' | ';
  }
  echo 'content here';
}
?>

答案 3 :(得分:0)

仅使用ternary operators

<?php echo !empty($box1) ? ( !empty($box2) ? ' | ' : '' ) . 'content here' : '' ?>
相关问题