[英]PHP Syntax to shorten if-statements
免責聲明:以下是一種不好的做法(但在非常非常具體的用途中會很有用)
有沒有辦法縮短(以一種不太好但更短的方式)if 語句:而不是:
if(5 == $foo){
$b = 98;
$c = 98 * $otherVariable;
//do something complex
doSomethingElse($b, $c);
}
這個例子會變得更短,即使它是由 IDE 格式化的。 它會變成這樣(但這不起作用):
(5 == $foo) && { $b = 98;
$c = 98 * $otherVariable;
//do something complex
doSomethingElse($b, $c);}
我建議,你應該選擇可讀性更好的代碼,但如果你想做一些不同的事情,你可以通過以下方式:
($foo == 5) && doSomethingElse(98, 98*$otherVariable);
或者
PHP 三元運算符
($your_boolean) ? 'This is true' : 'This is false';
你可以像下面這樣重寫你的if
語句:
($foo == 5) ? doSomethingElse(98, 98*$otherVariable) : "";
// little shorter but not better readable
($foo != 5) ? : doSomethingElse(98, 98*$otherVariable);
檢測結果:
$ cat test.php
<?php
function aa(){ echo "123\n"; }
$foo = 5;
// this will not call aa()
($foo == 4) && aa() ;
// this will call aa()
($foo == 5) && aa() ;
?>
$ php test.php
123
if(5 == $foo) doSomethingElse(98, 98*$otherVariable);
當心! 變量$b
和$c
不可用於進一步計算!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.