我正在尝试将一个变量传递到包含文件中。我的主机更改了PHP版本,现在我尝试的任何解决方案都无法工作。
我想我已经试过了所有我能找到的选择。我肯定这是最简单的事!
变量需要从调用的第一个文件中设置和计算(它实际上是$_SERVER['PHP_SELF'],需要返回该文件的路径,而不是包含的second.php)。
选项1
在第一个文件中:
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。
我遗漏了什么?
谢谢!
发布于 2017-08-08 08:48:26
您可以使用提取()函数
Drupal在其主题()函数中使用它。
这里是一个带有$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 er.php :
<h1><?php echo $title; ?></h1>发布于 2012-08-10 15:55:11
选项3是不可能的-您将得到.php文件的呈现输出,就像在浏览器中单击该url一样。如果您获得了原始PHP代码(如您所愿),那么您的站点的所有源代码都将被公开,这通常不是一件好事。
选项2没有多大意义--您将把变量隐藏在函数中,并且受制于PHP的变量范围。您还必须有$var = passvariable()的某处,才能将“内部”变量转换为“外部”变量,然后回到原点。
备选案文1是最实际的。include()基本上会在指定的文件中关闭并在那里执行,就好像文件中的代码实际上是父页面的一部分一样。它看起来确实是一个全局变量,这里的大多数人都不赞成这个变量,但是根据PHP的解析语义,这两个变量是相同的:
$x = 'foo';
include('bar.php');和
$x = 'foo';
// contents of bar.php pasted here发布于 2012-08-10 15:59:13
考虑到php中最基本级别的包含状态从文件中获取代码并将其粘贴到您调用它的位置,并且include手册声明如下:
当包含文件时,它包含的代码继承了发生包含的行的变量范围。从那时起,调用文件中该行中的任何可用变量都将在被调用文件中可用。
这些事情使我认为,这是一个完全不同的问题。另外,选项3将永远不会工作,因为您没有重定向到second.php,您只是包含它,选项2只是一个奇怪的工作围绕。php中包含状态的最基本示例是:
vars.php
<?php
$color = 'green';
$fruit = 'apple';
?>
test.php
<?php
echo "A $color $fruit"; // A
include 'vars.php';
echo "A $color $fruit"; // A green apple
?>考虑到第一个选项最接近这个例子(尽管比应该更复杂),而且它不起作用,这使我认为您在include语句中犯了一个错误(相对于根或类似的问题,错误路径)。
https://stackoverflow.com/questions/11905140
复制相似问题