问题描述:

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

网友答案:

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.

网友答案:

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...

相关阅读:
Top