Evaluate a string as PHP code?

∥☆過路亽.° 提交于 2019-12-20 01:44:46

问题


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

回答1:


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



回答2:


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



回答3:


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()
?>


来源:https://stackoverflow.com/questions/9831073/evaluate-a-string-as-php-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!