-1

What is the best way to go about defining a php function and the call to that function, in a string, and then executing that code i.e., eval? I'm trying to get the length of an encoded uri out of a function defined and called in a string.

$json_arr['my_function'] = "function hashfun1($enc_uri) { return strlen($enc_uri); } hashfun1($enc_uri);";
$hash_func = $json_arr['my_function'];
$hash_val = eval($hash_func);
print_r($hash_val); // should be length of encoded uri but displays "Parse error: syntax error, unexpected '%', expecting '&' or T_VARIABLE"
exit;

Thanks.

neridaj
  • 2,143
  • 9
  • 31
  • 62
  • 2
    I don't understand what you're trying to accomplish with that code. Why do you need `eval()` in the first place? – Amal Murali Feb 19 '14 at 20:18
  • No parse error here. Lots of other errors. – AbraCadaver Feb 19 '14 at 20:18
  • Why, in first place, you're doing it using `eval`? – baldrs Feb 19 '14 at 20:19
  • 4
    Why is your function stored in a string? Where is that string coming from? Remember, "if `eval()` is the answer, you're almost certainly asking the wrong question". – gen_Eric Feb 19 '14 at 20:19
  • What is `$enc_uri`? Where is it coming from? – gen_Eric Feb 19 '14 at 20:20
  • The function is being returned as a json response from a rest service. I need to use the function returned to get the length of an encoded uri: `function encodeURIComponent($str) { $revert = array('%21'=>'!', '%2A'=>'*', '%27'=>"'", '%28'=>'(', '%29'=>')'); return strtr(rawurlencode($str), $revert); }` – neridaj Feb 19 '14 at 20:27

3 Answers3

0

I guess you want:

$json_arr['my_function'] = "function hashfun1($enc_uri) { return strlen($enc_uri); } hashfun1('" . $enc_uri . '");";

You missed to populate $enc_uri.

Don't do this in production code, although it works. eval() is evil. You have been warned.

Community
  • 1
  • 1
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
0

you need to escape "$" in double-quoted string. And check number of returns (second for eval):

$json_arr['my_function'] = "function hashfun1(\$enc_uri) { return strlen(\$enc_uri); } return hashfun1(\$enc_uri);";
Michael Livach
  • 518
  • 3
  • 13
  • and why you use eval? It breaks opcode cache and makes sense in rare cases. If you look for dynamic function generation, check this: (old) http://php.net/create_function http://php.net/call_user_func_array (new) http://php.net/manual/en/functions.anonymous.php – Michael Livach Feb 19 '14 at 20:33
0

I guess I need to use call_user_func(); This worked for me: $json_arr['my_function'] = function($enc_uri) { return strlen($enc_uri); }; $hash_val = call_user_func($json_arr['my_function'], $enc_uri); print_r($hash_val); exit;

Thanks for the help guys.

neridaj
  • 2,143
  • 9
  • 31
  • 62