user81993 user81993 - 1 year ago 58
PHP Question

Is there a way to turn a string into a function during runtime?

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);

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.

Sam Sam
Answer Source
$src = '$say_message = function($message) { echo $message; };';

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;');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download