0

I am trying to setup an array that pulls the filename and function name to run, but it not fully working.

The code is

$actionArray = array(
    'register' => array('Register.php', 'Register'),
);

if (!isset($_REQUEST['action']) || !isset($actionArray[$_REQUEST['action']])) {
    echo '<br><br>index<br><br>';
    echo '<a href="?action=register">test</a>';
    exit;
}

require_once($actionArray[$_REQUEST['action']][0]);
return $actionArray[$_REQUEST['action']][1];

Register.php has

function Register()
{
    echo 'register';

}


echo '<br>sdfdfsd<br>';

But it does not echo register and just sdfdfsd.

If I change the first lot of code from

return $actionArray[$_REQUEST['action']][1];

to

return Register();

It works, any ideas?

Thanks

2
  • don't use $_REQUEST, use $_GET or $_POST instead. Commented Mar 13, 2013 at 21:16
  • The code was from SMF forum software, I was just playing around with it, the only bit I changed was the echo Commented Mar 13, 2013 at 21:22

2 Answers 2

3

Change the last line to:

return call_user_func($actionArray[$_REQUEST['action']][1]);

This uses the call_user_func function for more readable code and better portability. The following also should work (Only tested on PHP 5.4+)

return $actionArray[$_REQUEST['action']][1]();

It's almost the same as your code, but I'm actually invoking the function instead of returning the value of the array. Without the function invocation syntax () you're just asking PHP get to get the value of the variable (in this case, an array) and return it.

Sign up to request clarification or add additional context in comments.

Comments

0

You'll find something usefull here: How to call PHP function from string stored in a Variable

Call a function name stored in a string is what you want...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.