简体   繁体   English

比多个如果更好的方法?

[英]Better way than multiple if?

A better way than multiple if condition in php? 有更好的方法比在PHP中使用if多重条件? Is too many if condition there, so i need something more simple and efficient...and you can show me examples?! 如果条件太多了,那么我需要更简单有效的方法...并且您可以向我展示示例?

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();
                         }
}

The thing about code is that you can tackle one problem in many different ways. 关于代码的问题是,您可以通过许多不同的方式解决一个问题。 It is all justified depending on the environment and how you want to organise your problem and the dimension of your project. 根据环境以及您要如何组织问题和项目的规模,这都是合理的。

So, for example, as mentioned in the comments, a good replacement for if conditions are switch cases . 因此,例如,如注释中所述, if conditionsswitch cases ,则可以很好地替代。

Switch cases example 开关箱示例

I am not aware of the entire structure behind your question, but I will provide a solution on how I would do it. 我不知道您问题背后的整个结构,但是我将提供解决方案。

/**
 * @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');

    }
}

The only reason why i grouped the switch cases is because nothing seemed to change in your code that would justify clear separation, BUT to make you aware you can both separate the cases to be very specific depending on your IDs OR group certain IDS if only a few behave equally, while separating specific IDS for very specific behaviours. 我将转换用例归为一组的唯一原因是,您的代码中似乎没有什么变化可以证明明确的分隔是合理的,但是要使您知道,您可以根据您的ID来分隔两​​个特定的个案,或者仅对一个ID进行分组很少有相同的行为,而将特定IDS分离为非常特定的行为。

Method calls 方法调用

This scenario is just a different way to tackle the same problem. 这种情况只是解决同一问题的另一种方式。 Just for giggles and playfulness of it :) I am sure it has its own play cases, just like get_class can avoid us to constantly create a switch case for factory classes, but as mentioned before, it all depends on your idea :) 只是因为它的傻笑和有趣:)我确信它具有自己的播放案例,就像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'];
    }

}

Hope it helps you giving some ideas on how you can tackle this or find a solution that best suits you! 希望它能帮助您就如何解决此问题或找到最适合您的解决方案给出一些想法! :) :)

NOTE: I know it is not mentioned, BUT if you are using the $_GET['id'] do do some kind of access to DBs or execute system commands do not forget the possibility of system breach and sql injection . 注:我知道这是没有提及,但如果您使用的是$_GET['id']不要做一些访问的DBs或执行system commands ,不要忘记的可能性, system breachsql injection Never trust variables external to the system 永远不要信任系统外部的变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM