清洁并优化if


Clean and optimize if

我的页面中有这段代码,但我想优化它,因为它太长了。你能给我看一种不同的写法吗?

public function __construct($css, $info, $other){
    if ($info != FALSE) {
          echo "Info is True";
    }
    if ($css != FALSE) {
          echo "Css is true";
    }
    if ($other != FALSE) {
          echo "other is true";
    }
}

这只是一个例子。该代码有太多的if条件,因为我必须检查的字段不同。有不同的方法吗?

我尝试过其他方法,但没有成功。编辑:有些时候变量是空的!

您的代码足够清晰,但您可以尝试不同的表示方式,如:

public function __construct($css, $info, $other){
    echo $info != FALSE ? 'Info is True' : 'Info is False';
    echo $css != FALSE ? 'CSS is True' : 'CSS is False';
    echo $other != FALSE ? 'Other is True' : 'Other is False';
}

如前所述,您现有的代码足够清晰(可能还有您应该使用的代码),但为了好玩,您可以通过使用变量使其变得很短:-)

class Foo
{
    public function __construct($css, $info, $other)
    {
        foreach (array('css', 'info', 'other') as $p)
            if (!!$$p) echo "$p is true" . PHP_EOL;
    }
}
$bar = new Foo(1, '', true);

输出:

css is true
other is true

为了避免大量的ifs,您可以使用一个单独的函数来echo所需的文本,例如:

public function __construct($css = false, $info = false, $other = false) {
    $this->echoIfTrue($css, "Css is true");
    $this->echoIfTrue($info, "Info is true");
    $this->echoIfTrue($other, "Other is true");
}
private function echoIfTrue($someVar, $textToEcho) {
    if ($someVar) {
        echo $textToEcho;
    }
}