简体   繁体   中英

Better way than multiple if?

A better way than multiple if condition in php? 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 .

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.

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 :)

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 . Never trust variables external to the system

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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