Reputation: 8289
I have a string that I want to have PHP read as a piece of code. The reason is that I want to build the set of instructions for PHP in advance, and then execute it later on. Currently I have:
$string = '$this->model_db->get_results()';
And the desired result is:
$string2 = $this->model_db->get_results();
Upvotes: 3
Views: 8972
Reputation: 43380
It sounds like you want PHP's eval function, which executes a string containing 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 to say, there are much better ways to do things you might think to do with eval
.
In the example above, you have to make sure $this
is in scope in the code calling eval
. This means if you try to eval($get_results)
in a completely different part of the code, you might get an error about $this
or $this->model_db
not existing.
A more robust 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
isn't 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);
Upvotes: 4
Reputation: 19251
you can have a variable variable/function, but cannot have variable method chains. you can however create a method chain using variable variables/functions.
Check this page of the php documentation: http://php.net/manual/en/language.variables.variable.php
it shows the usage of using strings as object or method names. using eval may lead to security vulnerabilities depending on the source of your data.
$var1 = 'model_db';
$var2 = 'get_results';
$this->$var1->$var2();
Upvotes: 4
Reputation: 2024
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()
?>
Upvotes: 1