0

say I had this

$src = "function($message) { echo $message; }"

I'm looking for a way to turn the source as a string into an actual function during runtime, sorta like

$say_message = magic_command($src);
$say_message("hello");

but I haven't found a way to do it.

If you're pondering the purpose, I'm extracting data from a large string. To make it simpler to change the procedure, I created an intermediary language(regex really won't do here) which I'm just eval'ing right now. I figured turning the procedure into a php native function might speed up the processing.. worth a shot. Security is not a concern, I'm the only one using this.

2
  • 2
    eval() would the function you are looking for: php.net/manual/en/function.eval.php Commented Oct 23, 2016 at 0:21
  • doh, didn't think of that Commented Oct 23, 2016 at 0:26

1 Answer 1

1
$src = '$say_message = function($message) { echo $message; };';
eval($src);
$say_message("hello");

This is the actual way to get $say_message to work as a function through string, you have to use eval(), make sure you add the proper ; in the code

There is also another way to create it but not from a single string, using create_function()

$say_message = create_function('$message','echo $message;');
$say_message("hello");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.