开发者

How can I call and execute a function stored in the database?

I have function getArray(pram1, pram2) stored in database (MySQL) and it returns data in an array. When I pass the query, it returns the function name as I stored it in the database, but does not execute this function.

The code, which I'm using, is this:

$result=eval("return \$ret = $db_query_function;");
$db_query_function is variable开发者_如何学编程 that have function name getArray(pram1, pram2).

Error generated eval()'d code


You'll have to use call_user_func().

call_user_func('function_name', $parameter);


Firstly, it's probably not the best solution to store functions in the database.

If you want to store function implementations in the database, you'll have to store only the function body and parameter list separately, (but no name should be given to the function) so you can use create_function to put your function into a variable at runtime.

for example:

function add($a, $b)
{
    return $a + $b;
}

should end up in variables similar to:

$arguments = '$a, $b'; // note single quotes, no variable expansion!
$implementation = 'return $a + $b;'; // single quotes again

$myFunction = create_function($arguments, $implementation);

now you can call your function:

$sum = $myFunction(10, 20); // $sum will now hold 30

If you just want your code stored in the database to be run, all you need is eval.

In both cases, you're most likely (but not definitely) missing a better/easier way to deal with yout code. In your sample, the most likely error is that pram1 and pram2 require a dollar sign in the string, but the code sample is incomplete enough to be sure. could also be that the function doesn't exist or you're missing a semicolon, or...

try:

$result = eval('return '.$db_query_function);

getArray(pram1, pram2).

Good luck.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜