想象一下,我们有2个文件,其中一个1.php使用以下代码调用:
<?php
$hello = "Hello from 1";
?>
Run Code Online (Sandbox Code Playgroud)
并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;
?>
Run Code Online (Sandbox Code Playgroud)
那么它的2.php作用是加载内容1.php并评估其中的php代码.现在我要做的是在评估期间1.php,变量$ hello更改为"hello from 1".但是如果你执行2.php你总是得到:
"hello from 2"
"hello from 2"
Run Code Online (Sandbox Code Playgroud)
而不是得到
"hello from 2"
"hello from 1"
Run Code Online (Sandbox Code Playgroud)
有没有人遇到过这个问题,如果有的话,你会怎么解决?
有一种更容易的方法来做到这一点.使用PHP include.
1.PHP
<?php
$hello = "Hello from 1";
?>
Run Code Online (Sandbox Code Playgroud)
2.PHP
<?php
$hello = "hello from 2";
echo $hello;
include '1.php';
echo $hello;
?>
Run Code Online (Sandbox Code Playgroud)
更新(未测试):
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;
Run Code Online (Sandbox Code Playgroud)