清理和优化如果
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
个条件,因为我要检查的字段不同。有其他方法吗?
我尝试过其他方法,但没有成功。
编辑:有时变量是空的!
为避免大量 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;
}
}
您的代码足够清晰,但您可以尝试不同的表示形式,例如:
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
我的页面中有这段代码,但我想优化它,因为它太长了。你能告诉我另一种写法吗?
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
个条件,因为我要检查的字段不同。有其他方法吗?
我尝试过其他方法,但没有成功。 编辑:有时变量是空的!
为避免大量 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;
}
}
您的代码足够清晰,但您可以尝试不同的表示形式,例如:
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