假设我们有两个文件,其中一个文件名为1.php,代码如下:
<?php
$hello = "Hello from 1";
?>和2.php,代码如下:
<?php
function LoadPage( $page )
{
$f = fopen( $page, 'r+' );
$content = fread( $f, filesize($page) );
fclose( $f );
return $content;
}
function GetEvalContent( $content )
{
$var = "";
ob_start();
eval( "?>" . $content . "<?" );
$var = ob_get_contents();
ob_end_clean();
return $var;
}
$hello = "hello from 2";
echo $hello . '<br/>';
$content = LoadPage( '1.php' );
GetEvalContent( $content );
echo $hello;
?>所以2.php所做的就是加载1.php的内容并计算其中的php代码。现在我想做的是,在1.php的求值过程中,变量$hello变为"hello from 1“。但是,如果您执行2.php,您总是会得到:
"hello from 2"
"hello from 2"而不是得到
"hello from 2"
"hello from 1"以前有人遇到过这个问题吗?如果有,你会如何解决它?
发布于 2011-08-04 05:27:51
有一种更简单的方法可以做到这一点。使用PHP的include。
1.php
<?php
$hello = "Hello from 1";
?>2.php
<?php
$hello = "hello from 2";
echo $hello;
include '1.php';
echo $hello;
?>更新(未测试):
function includeFile($file){
global $hello; // Use the global variable $hello
// this will make the include sets $hello correctly
ob_start();
include $file; // Remember any variables set here will be in this scope,
// not the global scope (unless you add them to the global line above)
$var = ob_get_contents(); // This will contain anything echoed to the screen
// from the included file
ob_end_clean();
return $var;
}
$hello = "hello from 2";
echo $hello;
$file = '1.php';
$output = includeFile($file);
echo $hello;
echo $output;发布于 2011-08-04 05:28:19
您是在一个函数中执行eval()的,因此所包含文件中的$hello将只是该函数作用域的一部分。它不会影响在函数外部定义的$hello (即全局作用域)。
您需要将global关键字放入包含文件中,除非您想要编写自己的PHP解析器来确定包含文件中定义了哪些变量并自动将它们全球化。
然而,从更大的角度来看...为什么?eval是一个可怕的邪恶丑陋的构造,您正在将自己暴露在调试痛苦的世界中,更不用说安全问题了。
发布于 2011-08-04 05:30:36
你有没有考虑过使用require或include?PHP Manual
示例:
$hello = "Hello from 2";
echo $hello;
include("1.php");
echo $hello;https://stackoverflow.com/questions/6933500
复制相似问题