要包含的 PHP 传递变量

标签 php variables include global-variables global

我正在尝试将变量传递到 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/

相关文章:

php - 使用 PHP 在亚马逊上进行 Mysqldump

c - 静态变量存储在哪里?

javascript - 如何在删除换行符的同时将 HTML 文本转换为 Javascript 变量?

c++ - 双项目解决方案中的 Visual Studio : Include . h 或 .cpp

c++ - 如何在 cpp 中导入/包含字符串

php - 使用 jquery 时,表单字段未发布到 php 文件

php:如何只读取目录中的txt文件

ruby - 变量声明: difference between "@@" and "class << self"

lua - require 语句正在覆盖 lua 中的全局变量

php - 使用 Slim 框架提供图像/ Assets