Php coding help

Discussion in 'Scripts, 3rd Party Apps, and Programming' started by taekwondokid42, Apr 2, 2010.

  1. taekwondokid42

    taekwondokid42 New Member

    Messages:
    268
    Likes Received:
    0
    Trophy Points:
    0
    I am wondering if there is a way to modify a function with code, for example a forloop or something.

    Example:

    function dostuff() {
    otherfunction1;
    otherfunction2;
    otherfunction5;
    }

    based on user input (which could be infinitely varied), I want to be able to change dostuff(), so that in one case it would call of5 first and then of2 and not call of1 at all.

    Am I clear and is this possible?
     
  2. gomarc

    gomarc Member

    Messages:
    516
    Likes Received:
    18
    Trophy Points:
    18
    Check out Variable Functions

    It may be what you are looking for.

    Edit:

    Here you have an example:

    PHP:
    <?php
    function test1(){
        echo 
    "This is function 1" "<br/>";
    }

    function 
    test2(){
        echo 
    "This is function 2" "<br/>";
    }

    function 
    test3(){
        echo 
    "This is function 3" "<br/>";
    }

    function 
    dostuff($stuff){
      
    reset($stuff); //Make sure it starts at the beginning
      
    while( key($stuff) !== NULL )
      {
        
    $do current($stuff);
        
    $do(); // Here is where each function is called.
      
    next($stuff);
      }
    }


    // Change $stuff to the functions you want to call
    $stuff = array('test1','test3');

    //Test the variable function
    dostuff($stuff);
    /*
    Output will be:
    This is function 1
    This is function 3
    */

    ?>

     
    Last edited: Apr 2, 2010
  3. misson

    misson Community Paragon Community Support

    Messages:
    2,572
    Likes Received:
    72
    Trophy Points:
    48
    In addition to variable functions, there are call_user_func, call_user_func_array and even ReflectionMethod. Just be careful not to set the function name directly from user input, else you'll be opening your script to injection.

    PHP:
    $allowedThings array_flip(array('aFunc''anotherFunc''yaf', ...));

    function 
    dostuff($stuff) {
        foreach (
    $stuff as $thing => $args) {
            if (
    is_array($args)) {
                
    call_user_func_array($thing$args);
            } else {
                
    call_user_func($thing$args);
            }
        }
    }

    $stuffToDo array_intersect($stuff$_REQUEST[]);
    dostuff($stuffToDo);
     
    Last edited: Apr 3, 2010

Share This Page