tags:

views:

118

answers:

5

I recently created a site that simply has a variable and checks it against various possible values and gives an appropriate response. The program goes through using a lot of else if statements.

I'm sure there is a better method of doing this, but not sure what to use. I'm still learning PHP really.

Here's the source code to give you a better idea:

http://github.com/r3morse/isitup/blob/a7a972bcf125d1f058a44406a467438d46aa4b16/functions.php

+5  A: 

Probably switch is what you're after, it is equivalent to if... else if... .

http://be.php.net/switch

Vincent De Baere
Thanks, that looks perfect!
Sam
A: 

Try State or Chain-of-responsibility

Anton Gogolev
A: 

If every code need a different operation, i dont think you can disguise the else..if structure..

You could use a switch

switch($code){
case "200":
  //then you code
 break;
case "401":
  //other code
 break;
}

and so on.. but i dont think you'll gain something relevant..

Other way can be store alle the code inside an array, indexed like $code => $message.. but only if you just print something for each code.

DaNieL
A: 

another possibility would be to define an object with for the appropriate actions and dispatch.

like ...

<?php
    class Dispatcher {
        public function action_404($code) {
            return 'foo bar ' . $code;
        }

        public function action_200($code) {
            return 'far boo ' . $code;
        }

        public function action_301($code) {
            return $this->action_200($code);
        }

        /* and so on */

        public function unknownAction($code) {
            return 'don\'t know ' . $code;
        }

    }

    $code       = (int)$_REQUEST['code'];
    $methodName = 'action_' . $code;
    $dispatcher = new Dispatcher();

    if (method_exists($dispatcher, $methodName)) {
        $result = $dispatcher->$methodName($code);
    } else {
        $result = $dispatcher->unknownAction($code);
    }

    echo $result;
?>

doesn't really makes sense in your case tough.

Schnalle