1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Can this be done? [PHP]

Discussion in 'HTML, Graphics & Programming' started by JonD, 6 Jun 2006.

  1. JonD

    Wise Guy

    Joined: 26 Jun 2003

    Posts: 1,142

    Location: North West

    On my pages i usually do a big if/else/switch to decide which function to call

    PHP:
    if ($_GET['action'] == 'whatever')
      
    doThis();
    else if (
    $_GET['action'] == 'bob')
      
    doThis2();
    Is it possible to do sumthing like this:

    $action['whatever'] = doThis();
    $action['bob'] = doThis2();

    Then how would I call the appropiate function to be called depending on the value of $_GET['action']?

    Is it possible?

    Is there another way to do what I want with less/tidy/efficient code?

    Thx
     
  2. JonD

    Wise Guy

    Joined: 26 Jun 2003

    Posts: 1,142

    Location: North West

    Ok i found a way, however if $_GET['action'] isnt set or is set to a value that is not in the array then i recieve an error. How could I get around this?

    Again this may not be the best way to do it so if anyone has another method, please share. :D

    PHP:

    function login() { } 
    function 
    logout() { }
    function 
    registrationForm() { }

    $_action['login']    = 'login';
    $_action['logout']   = 'logout';
    $_action['register'] = 'registrationForm';

    call_user_func($_action[$_GET['action']]);
    Thx
     
  3. NightmareXX

    Wise Guy

    Joined: 12 Aug 2005

    Posts: 1,025

    Location: Team 10

    1st method. Only thing that changes is the last if statement.
    PHP:
    if(isset($_GET['action'])){
      
    $action $_GET['action'];
    }

    if(
    $action == "whatever"){
      
    DoThisFunction();
    }
    elseif(
    $action == "me"){
      
    ExecuteMe();
    }
    2nd method
    PHP:
    if($action){
      
    DoThisFunction($action);
    }
     
  4. Beansprout

    Man of Honour

    Joined: 31 Jan 2004

    Posts: 16,313

    Location: Plymouth

  5. Augmented

    Soldato

    Joined: 18 Oct 2002

    Posts: 5,464

    Location: London Town

    If you've got a large block of if/else statements with fixed values to compare to, always go with a switch statement for efficiency. Its faster since PHP doesn't need to evaluate evaluate every conditional once a statement returns true. For further efficiency, put the most commonly executed cases at the top so it has fewer lines of code to run through in most executions.

    Code:
    <?php
    switch ($_GET['action']) {
    case 'login':
       login();
       break;
    case 'logout':
       logout();
       break;
    default:
       echo 'Hello new user';
    }
    ?> 
    default is the fallback block used when no case matches.

    /edit - Also, when using isset() as Beansprout mentioned, opt for a ternary operator for more concise code:
    Code:
    $action = isset($_GET['action']) ? $_GET['action'] : null;
    Neater than an if/else. Though I'd use an !empty() instead of isset() as you only really want to act on valid values for $_GET['action'].
     
    Last edited: 7 Jun 2006
  6. Dj_Jestar

    Caporegime

    Joined: 18 Oct 2002

    Posts: 28,940

    Location: Back in East London

    Augmented's example is much preferred, however this is a sneaky chance to introduce function_exists :)

    Code:
    <?php
    
    if ((isset($_GET['action'])) && (function_exists($_GET['action']))) {
        call_user_func($_GET['action']);
    } else {
        DefaultFunction();
    }
    
    ?>

    EDIT:

    On the note of concise.. you can use variable functions and void the need to use call_user_func() at all:
    http://us2.php.net/manual/en/functions.variable-functions.php
    Code:
    <?php
    
    @$_GET['action']();
    
    ?>
    but that is just .. meh, as far as good practice goes :)
     
    Last edited: 7 Jun 2006
  7. Beansprout

    Man of Honour

    Joined: 31 Jan 2004

    Posts: 16,313

    Location: Plymouth

    But then what happens if I request /foo.php?action=bulkEmail() or similar?

    Though good app design would prevent that, I'd filter it through an array of predefined actions with in_array() or a switch.

    Augmented - hehheh depends if he'll ever use 0 though, so I reckoned isset() was better to show him generally (the notes on the PHP page are great) :)
     
  8. Dj_Jestar

    Caporegime

    Joined: 18 Oct 2002

    Posts: 28,940

    Location: Back in East London

    It was a quick example to introduce function_exists(), that is all. I'm lazy and cba to type out a filter when I've already said Augmented's switch() example is better.
     
  9. Beansprout

    Man of Honour

    Joined: 31 Jan 2004

    Posts: 16,313

    Location: Plymouth

    I guess I'm just anti-lazy this morning :D

    Probably something to do with waking up 2hrs before I was supposed to. Grr.
     
  10. JonD

    Wise Guy

    Joined: 26 Jun 2003

    Posts: 1,142

    Location: North West

    Ill have a look at the in_array() and isset() stuff.

    Id know i could do it with if/else/switches but I find the code quite ugly and hard to organise etc, which is why I thought the array idea would be good.

    ---

    The following method seems to work, can anyone spot a time where it will fail?

    PHP:
    $_action = array (
        
    ''         => 'login',
        
    'login'    => 'login',    
        
    'logout'   => 'logout',    
        
    'register' => 'registerForm'
    );    

    if (
    array_key_exists($_GET['action'], $_action))
        
    call_user_func($_action[$_GET['action']]);
    else
        
    header("Location: index.php");
    Thx
     
    Last edited: 7 Jun 2006
  11. Augmented

    Soldato

    Joined: 18 Oct 2002

    Posts: 5,464

    Location: London Town

  12. Beansprout

    Man of Honour

    Joined: 31 Jan 2004

    Posts: 16,313

    Location: Plymouth

    Good reading there. The second link in turn links to this post which I think gives a very good explanation :)
     
  13. Dj_Jestar

    Caporegime

    Joined: 18 Oct 2002

    Posts: 28,940

    Location: Back in East London

    An excellent book for MVC patterns is titled "Patterns of Enterprise Application Architecture"

    :)