Knuxchan
Knuxchan

Reputation: 69

PHP - Calling functions from an array?

This is what I currently have:

public function setUp() {
    $tests = array(
                'printHello'    =>  array(),    
                'printWorld'    =>  array(),
                'printName' =>  array('Bob'),
            );
}


public function printHello() {
echo "Hello, ";
}

public function printWorld() {
echo "World!";
}

public function printName($name=false) {
echo $name;
}

What I want to do is loop through all the functions and run them consecutively. This is what I had to end up doing, but it just seems like there should be a more efficient way to do this:

foreach($tests as $test=>$parameters) {
    $num_params = count($parameters);
    switch($num_params) {
        case 0:
            $this->$test();
            break;
        case 1:
            $this->$test($parameters[0]);
            break;
        case 2:
            $this->$test($parameters[0],$parameters[1]);
            break;
        case 3:
            $this->$test($parameters[0],$parameters[1],$parameters[2]);
            break;
        default:
            echo "Error! More than 3 parameters for function" . $test . "!";
            exit;
    }       
}

I am using PHP 5.3. Is there a more efficient way to call the functions in a loop?

EDIT: I can't use call_user_func_array because I'm calling non-static methods from within their parent class. Is there another way?

Upvotes: 2

Views: 170

Answers (2)

hakre
hakre

Reputation: 197712

One thing there is is called

this should help you prevent the switch for the parameter count already.

The rest is a simple foreach-loop

foreach ($tests as $method => $parameters) 
{
    $callback = array($this, $method);
    call_user_func_array($callback, $parameters);
}

Upvotes: 2

nickb
nickb

Reputation: 59699

You're looking for call_user_func_array():

foreach($tests as $test=>$parameters) {
    call_user_func_array( array( $this, $test), $parameters);
}

Loading this into a simple test class:

class Test {
    public function setUp() {
        $tests = array(
            'printHello'    =>  array(),    
            'printWorld'    =>  array(),
            'printName' =>  array('Bob'),
        );
        foreach( $tests as $fn => $params) 
            call_user_func_array( array( $this, $fn), $params);
    }

    public function printHello() {
        echo "Hello, ";
    }

    public function printWorld() {
        echo "World!";
    }

    public function printName($name=false) {
        echo $name;
    }
}

We can see that this outputs for PHP >= 5.0.0:

Hello, World!Bob

Upvotes: 2

Related Questions