Php coding help

taekwondokid42

New Member
Messages
268
Reaction score
0
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?
 

gomarc

Member
Messages
516
Reaction score
18
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:

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
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:
Top