2012-03-22 84 views
3

我有一个字符串,我想PHP阅读为一段代码。原因是我想提前为PHP创建一组指令,然后再执行它。目前,我有:评估一个字符串为PHP代码?

$string = '$this->model_db->get_results()'; 

和期望的结果是:

$string2 = $this->model_db->get_results(); 
+1

如果'eval'为你的任务的解决方案 - 你肯定错了 – zerkms 2012-03-22 22:24:18

+0

您正在使用什么版本的PHP做什么? – 2012-03-22 22:31:34

回答

4

你可以有一个变量变量/函数,但不能有变量方法链。您可以使用变量变量/函数创建一个方法链。

选中此页面中的PHP文件: http://php.net/manual/en/language.variables.variable.php

它显示了使用字符串作为对象或方法名称的使用。使用eval可能会导致安全漏洞,具体取决于您的数据来源。

$var1 = 'model_db'; 
$var2 = 'get_results'; 

$this->$var1->$var2(); 
+0

虽然说实话,但如果不使用上述方法,可能会有更好的解决方案。 – dqhendricks 2012-03-22 22:27:30

+0

我打算剔除这个,看起来更简单,可能更有效。感谢这两个建议。 – Malcr001 2012-03-22 22:28:54

1

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"; 
?> 

或者在你的情况下:

<?php 
    $string = "\$string2 = \$this->model_db->get_results();"; 
    // ... later ... 
    eval($string); 
    // Now $string2 is equal to $this->model_db->get_results() 
?> 
+1

不...不要使用评估这个... – dqhendricks 2012-03-22 22:16:52

+0

埃瓦尔为我工作。 dqhendricks你建议什么呢? – Malcr001 2012-03-22 22:21:25

+0

@ user971824是的,eval的作品,但不好的做法。看到我的答案替代。 – dqhendricks 2012-03-22 22:26:09

4

这听起来像你想PHP的eval function,其执行包含PHP代码的字符串。例如:

// Now 
$get_results = '$this->model_db->get_results(' . intval($id) . ');'; 

// Later 
eval($get_results); 

然而,EVAL通常是一个坏主意。也就是说,有很多方法可以处理您可能会想到的与eval有关的事情。

在上面的示例中,您必须确保$this在调用eval的代码中。这意味着,如果你在代码中的一个完全不同的部分尽量eval($get_results),你可能会得到约$this$this->model_db不存在错误。

更健壮的替代方案是创建一个anonymous function(可在PHP 5.3及以上):

// Now 
$that = $this; 
$get_results = function() use ($that, $id) { 
    return $that->model_db->get_results($id); 
}; 

// Later 
call_user_func($get_results); 

但如果$this是现在没空?很简单:让一个函数参数:

// Now 
$get_results = function($that) use ($id) { 
    return $that->model_db->get_results($id); 
}; 

// Later 
call_user_func($get_results, $this);