Alan
Alan

Reputation: 399

PHP eval syntax

I need help figuring out the syntax for the eval function - or even if eval is the right approach. I have a column in my mysql database which holds the name of a PHP function I need to run. There are also PHP variables that would like to leave as variable until they are passed to the function. Below is what I have so far:

eval($valRec[$key]($key,$value));

$valRec is the array which contains the results of a mysql SELECT. $key is a variable which references the name of the column that contains the function name.

$key and $value are the PHP variables that I need to pass into the function.

In the end, I want to end up with:

functionName($key,$value);

which PHP should run.

Hopefully I explained it clearly - thank you in advance for any help!

Upvotes: 1

Views: 214

Answers (5)

xdazz
xdazz

Reputation: 160883

In php, you could do below;

$func = 'strtolower';
$foo = $func($bar);

So in your case, $valRec[$key]($key,$value); will just work.

Check the demo.

Addtion: The reason why your eval not work is because eval need to take a string as parameter, not don't forget ; to end the statement, or it will be syntax error. So you need to do:

eval($valRec[$key].'($key, $value);');

Upvotes: 2

Matthew
Matthew

Reputation: 48304

All you need to do is:

$valRec[$key]($key,$value);

Reference: variable functions.

Upvotes: 3

Barmar
Barmar

Reputation: 781721

Eval is probably not what you want. Look at call_user_func and call_user_func_array. They let you call a function whose name is in a variable.

call_user_func($valRec[$key], $key, $value);

Upvotes: 4

Matt Mitchell
Matt Mitchell

Reputation: 41833

I haven't used PHP recently, but the concept of eval is to evaluate a string.

As such, you need to create the string representing the line of code you want run.

In your case that means:

eval($valRec[$key] . '($key, $value);');

You've said it yourself, you want to end up with functionName($key,$value); so you need to make a string that is that, then pass it to eval.

Upvotes: 1

John Woo
John Woo

Reputation: 263803

see this example,

<?php
    $string = 'cup';
    $name = 'coffee';
    $str = 'This is a $string with my $name in it.';
    echo $str. "\n";
    eval("\$str = \"$str\";");
    echo $str. "\n";
?>

this is the output

This is a $string with my $name in it.
This is a cup with my coffee in it.

you need to read this, when is eval evil in php?

Upvotes: 0

Related Questions