我正在尝试将变量传递到 include 文件中。我的主机更改了 PHP 版本,现在我尝试的任何解决方案都不起作用。
我想我已经尝试了所有能找到的选项。我敢肯定这是最简单的事情!
需要从调用的第一个文件中设置和评估变量(它实际上是$_SERVER['PHP_SELF']
,并且需要返回该文件的路径,而不是包含的 second.php
)。
选项一
在第一个文件中:
global $variable;
$variable = "apple";
include('second.php');
在第二个文件中:
echo $variable;
选项二
在第一个文件中:
function passvariable(){
$variable = "apple";
return $variable;
}
passvariable();
选项三
$variable = "apple";
include "myfile.php?var=$variable"; // and I tried with http: and full site address too.
$variable = $_GET["var"]
echo $variable
这些都不适合我。 PHP版本是5.2.16。
我错过了什么?
谢谢!
最佳答案
您可以使用 extract() function
Drupal 在其 theme() 函数中使用它。
这里是一个带有 $variables
参数的渲染函数。
function includeWithVariables($filePath, $variables = array(), $print = true)
{
$output = NULL;
if(file_exists($filePath)){
// Extract the variables to a local namespace
extract($variables);
// Start output buffering
ob_start();
// Include the template file
include $filePath;
// End buffering and return its contents
$output = ob_get_clean();
}
if ($print) {
print $output;
}
return $output;
}
./index.php :
includeWithVariables('header.php', array('title' => 'Header Title'));
./header.php :
<h1><?php echo $title; ?></h1>
关于要包含的 PHP 传递变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11905140/