2011-04-30 25 views
1

我有兩個文件,如下面PHP - 的eval()問題

SomeClass.php

class SomeClass { 
    public function display() { 
    $content = file_get_contents("helloworld.php"); 
    eval($content); 
    } 

    public function helloWorld() { 
    echo "hello World!"; 
    } 

} 

helloworld.php

<?php 
    $this->helloWorld() ; 
?> 
<p>It's html expression</p> 

正如你所看到的,我試圖執行的HelloWorld。 PHP在顯示功能。 當然,因爲html標籤被放置在顯示函數中,所以發生錯誤。

有沒有什麼好的方法可以在保留helloworld.php代碼的顯示函數中執行helloworld.php文本?

+1

爲什麼不乾脆['require'(HTTP://www.php。淨/要求)'helloworld.php'? – icktoofay 2011-04-30 05:49:17

回答

1

您可以使用輸出緩衝來捕獲它。

ob_start(); 
include "helloworld.php"; 
$content = ob_get_contents(); 
ob_end_clean(); 
+0

謝謝。這是我想要的。 – webnoon 2011-04-30 10:05:55

2

如果您嘗試在當前代碼的上下文中執行特定文件,爲何不使用includerequire

請記住,如果eval是答案,問題是錯誤的。

如果你真的在這裏使用eval

eval('?>' . $content); 

應該工作。是的,您可以關閉並重新打開PHP標籤。這是某些模板引擎的工作原理。

1

沒有辦法做到這一點,除非你想做字符串連接。

我有這樣一些小的改動helloworld.php文件時,它的工作原理測試這樣的:

$this->helloWorld() ; 
?><p>It's html expression</p> 

這表明文本運行原料就好像它是很難包括在內。

現在,如果您不需要改變打開的<?php標記,您可以採用以下兩種方法之一。

最簡單的方法(字符串串聯):

public function display() { 
    $content = file_get_contents("helloworld.php"); 
    eval('?>' . $content); //append a php close tag, so the file looks like "?><?php" 
} 

更難的方式(字符串替換):

public function display() { 
    $content = file_get_contents("helloworld.php"); 

    //safely check the beginning of the file, if its an open php tag, remove it. 
    if('<?php' == substr($content, 0, 5)) { 
     $content = substr($content, 5); 
    } 
    eval($content); 
}