2011-04-28 62 views
1

我是新來的PHP,我想有一個條件語句,像這樣簡單的問題:php |在條件語句

if ($foo != 'Any') { $condition .= '$this_foo == $foo &&';} 
if ($bar != 'Any') { $condition .= '$this_bar == $bar &&';} 
if ($txt != 'Any') { $condition .= '$this_txt == $txt &&';} 
$condition .= '$num1 > 0 && $num2 < 1000'; 

if (...[php would parse the $condition variable]) 
{ 
    someoperations 
} 

什麼是正確的語法,if語句解析變量$條件?所以條件語句依賴於其他變量並防止長嵌套條件語句。

在此先感謝!

回答

2

嗯,它不是完全解析,但你可以評估你的條件作爲代碼執行。

$condition = true; 
if ($foo != 'Any') { $condition = $condition && ($this_foo == $foo);} 
if ($bar != 'Any') { $condition = $condition && ($this_bar == $bar);} 
if ($txt != 'Any') { $condition = $condition && ($this_txt == $txt);} 
$condition = $condition && ($num1 > 0 && $num2 < 1000); 

if ($condition) 
{ 
    someoperations 
} 

所以我們可以說這是$foo != 'Any'true,這將導致

$condition = true && ($this_foo == $foo) && ($num1 > 0 && $num2 < 1000); 

讓我們假設$this_foo == $foo$num1 == 45$num2 == 2300

$condition = true && true && (true && false); 
$condition = false; 

和你如果不會執行。

+1

+1。很好地解釋了 – Ben 2011-04-28 01:34:55

+0

感謝!它幫助了我。當我有名譽時,我會贊成這一點。 – iamebet 2011-04-28 16:03:35

+0

我們走了。我昨天才加入這裏,所以我是新手。 =) – iamebet 2011-04-28 16:53:16

0

我相信你想要的是

if (eval("return " . $condition)) {...} 

確保檢查錯誤情況下,如果解析失敗。