Evaluate string as PHP code?
I have a string that I want PHP to read as part of the code. The reason is that I want to create a set of instructions for PHP beforehand and then execute it later. I currently have:
$string = '$this->model_db->get_results()';
And the desired output:
$string2 = $this->model_db->get_results();
source to share
you can have a variable / function variable, but you cannot have method variable chaining. however you can chaining methods using variable variables / functions.
Check this php documentation page: http://php.net/manual/en/language.variables.variable.php
shows the use of strings as names for objects or methods. using eval can lead to security vulnerabilities depending on the source of your data.
$var1 = 'model_db';
$var2 = 'get_results';
$this->$var1->$var2();
source to share
It looks like you need the PHP function eval , which executes a string that contains PHP code. For example:
// Now
$get_results = '$this->model_db->get_results(' . intval($id) . ');';
// Later
eval($get_results);
However, eval is usually a bad idea . That is, there are much better ways to do what you can think of with eval
.
In the above example, you have to make sure to be $this
in scope in the calling code eval
. This means that if you try to execute eval($get_results)
in a completely different part of the code, you may get an error $this
or $this->model_db
not existing one.
A more reliable alternative would be to create an anonymous function (available in PHP 5.3 and up):
// Now
$that = $this;
$get_results = function() use ($that, $id) {
return $that->model_db->get_results($id);
};
// Later
call_user_func($get_results);
But what if $this
not available right now? Simple: make it a function parameter:
// Now
$get_results = function($that) use ($id) {
return $that->model_db->get_results($id);
};
// Later
call_user_func($get_results, $this);
source to share
http://php.net/manual/en/function.eval.php
<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
?>
Or in your case:
<?php
$string = "\$string2 = \$this->model_db->get_results();";
// ... later ...
eval($string);
// Now $string2 is equal to $this->model_db->get_results()
?>
source to share