[英]Better way than multiple if?
有更好的方法比在PHP中使用if多重條件? 如果條件太多了,那么我需要更簡單有效的方法...並且您可以向我展示示例?
if($_GET['id']=="4") {
try {
$ids = '4,246,226';
$notin = '1';
$parent_forum = 'php_forums.parent_id';
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
if($_GET['id']=="246") {
try {
$ids = '246';
$notin = '1';
$parent_forum = 'php_forums.parent_id';
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
if($_GET['id']=="226") {
try {
$ids = '226';
$notin = '1';
$parent_forum = 'php_forums.parent_id';
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
關於代碼的問題是,您可以通過許多不同的方式解決一個問題。 根據環境以及您要如何組織問題和項目的規模,這都是合理的。
因此,例如,如注釋中所述, if conditions
是switch cases
,則可以很好地替代。
開關箱示例
我不知道您問題背后的整個結構,但是我將提供解決方案。
/**
* @throws Exception
*/
public function doSomethingWithGET()
{
$notin = 1;
$parent_forum = 'php_forums.parent_id';
switch ($_GET['id']) {
case '4':
case '246':
case '226':
$ids = $_GET['id'];
break;
default:
throw new Exception('Specify your error message here');
}
}
我將轉換用例歸為一組的唯一原因是,您的代碼中似乎沒有什么變化可以證明明確的分隔是合理的,但是要使您知道,您可以根據您的ID來分隔兩個特定的個案,或者僅對一個ID進行分組很少有相同的行為,而將特定IDS分離為非常特定的行為。
方法調用
這種情況只是解決同一問題的另一種方式。 只是因為它的傻笑和有趣:)我確信它具有自己的播放案例,就像get_class
可以避免我們不斷為工廠類創建switch case
,但是如前所述,這完全取決於您的想法:)
class Test
{
/**
* @var array $idsAndActions
**/
protect $idsAndActions;
public function __construct ()
{
$this->idsAndActions = [
'4' => 'doSomethingWithGET',
'246' => 'doSomethingWithGET',
'226' => 'somethingDifferent',
];
}
public function parseGet ()
{
if (array_key_exists($_GET['id'], $this->idsAndActions)) {
$methodCall = $this->idsAndActions[$_GET['id']];
if (method_exists($this, $methodCall)) {
$this->$methodCall();
//add here more code for success events
}
}
echo '[Error] Your message';
//You can also throw an exception, which I would advice depending on who calls this :)
}
public function doSomethingWithGET ()
{
$this->notin = 1;
$this->parent_forum = 'php_forums.parent_id';
$this->ids = $_GET['id'];
}
public function somethingDifferent ()
{
$this->notin = 20;
$this->parent_forum = 'another_thing_here';
$this->ids = $_GET['id'];
}
}
希望它能幫助您就如何解決此問題或找到最適合您的解決方案給出一些想法! :)
注:我知道這是沒有提及,但如果您使用的是$_GET['id']
不要做一些訪問的DBs
或執行system commands
,不要忘記的可能性, system breach
和sql injection
。 永遠不要信任系統外部的變量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.