要包含的 PHP 传递变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11905140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP pass variable to include
提问by user1590646
I'm trying to pass a variable into an includefile. My host changed PHP version and now whatever solution I try doesn't work.
我正在尝试将变量传递到包含文件中。我的主机更改了 PHP 版本,现在我尝试的任何解决方案都不起作用。
I think I've tried every option I could find. I'm sure it's the simplest thing!
我想我已经尝试了我能找到的所有选项。我相信这是最简单的事情!
The variable needs to be set and evaluated from the calling first file (it's actually $_SERVER['PHP_SELF'], and needs to return the path of that file, not the included second.php).
该变量需要从调用的第一个文件中设置和评估(它实际上是$_SERVER['PHP_SELF'],并且需要返回该文件的路径,而不是包含的second.php)。
OPTION ONE
选项一
In the first file:
在第一个文件中:
global $variable;
$variable = "apple";
include('second.php');
In the second file:
在第二个文件中:
echo $variable;
OPTION TWO
选项二
In the first file:
在第一个文件中:
function passvariable(){
$variable = "apple";
return $variable;
}
passvariable();
OPTION THREE
选项三
$variable = "apple";
include "myfile.php?var=$variable"; // and I tried with http: and full site address too.
$variable = $_GET["var"]
echo $variable
None of these work for me. PHP version is 5.2.16.
这些都不适合我。PHP 版本为 5.2.16。
What am I missing?
我错过了什么?
Thanks!
谢谢!
回答by Marc B
Option 3 is impossible - you'd get the rendered output of the .php file, exactly as you would if you hit that url in your browser. If you got raw PHP code instead (as you'd like), then ALL of your site's source code would be exposed, which is generally not a good thing.
选项 3 是不可能的——你会得到 .php 文件的渲染输出,就像你在浏览器中点击那个 url 一样。如果您使用原始 PHP 代码(如您所愿),那么您网站的所有源代码都会暴露出来,这通常不是一件好事。
Option 2 doesn't make much sense - you'd be hiding the variable in a function, and be subject to PHP's variable scope. You'ld also have to have $var = passvariable()somewhere to get that 'inside' variable to the 'outside', and you're back to square one.
选项 2 没有多大意义 - 您会将变量隐藏在函数中,并受制于 PHP 的变量范围。您还必须在$var = passvariable()某个地方将“内部”变量置于“外部”中,然后您又回到了原点。
option 1 is the most practical. include()will basically slurp in the specified file and execute it right there, as if the code in the file was literally part of the parent page. It does look like a global variable, which most people here frown on, but by PHP's parsing semantics, these two are identical:
选项1是最实用的。include()基本上会在指定的文件中 slurp 并在那里执行它,就好像文件中的代码实际上是父页面的一部分。它确实看起来像一个全局变量,这里的大多数人都不喜欢它,但是通过 PHP 的解析语义,这两个是相同的:
$x = 'foo';
include('bar.php');
and
和
$x = 'foo';
// contents of bar.php pasted here
回答by thi3rry
You can use the extract() function
Drupal use it, in its theme() function.
您可以使用extract() 函数
Drupal 在它的 theme() 函数中使用它。
Here it is a render function with a $variablesargument.
这是一个带有$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 :
./index.php :
includeWithVariables('header.php', array('title' => 'Header Title'));
./header.php :
./header.php :
<h1><?php echo $title; ?></h1>
回答by Florin Stingaciu
Considering that an include statment in php at the most basic level takes the code from a file and pastes it into where you called it and the fact that the manual on include states the following:
考虑到 php 中最基本的 include 语句从文件中获取代码并将其粘贴到您调用它的位置,并且 include 手册中的说明如下:
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.
当一个文件被包含时,它包含的代码继承了包含发生所在行的变量范围。从那时起,调用文件中该行可用的任何变量都将在被调用文件中可用。
These things make me think that there is a diffrent problem alltogether. Also Option number 3 will never work because you're not redirecting to second.phpyou're just including it and option number 2 is just a weird work around. The most basic example of the include statment in php is:
这些事情让我觉得总有一个不同的问题。此外,选项 3 永远不会起作用,因为您没有重定向到second.php您只是包含它,而选项 2 只是一个奇怪的解决方法。php中include语句最基本的例子是:
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
?>
Considering that option number one is the closest to this example (even though more complicated then it should be) and it's not working, its making me think that you made a mistake in the include statement (the wrong path relative to the root or a similar issue).
考虑到第一个选项最接近这个示例(即使比它应该更复杂)并且它不起作用,这让我认为您在 include 语句中犯了错误(相对于根或类似的错误路径问题)。
回答by Daniel
I have the same problem here, you may use the $GLOBALS array.
我在这里遇到了同样的问题,您可以使用 $GLOBALS 数组。
$GLOBALS["variable"] = "123";
include ("my.php");
It should also run doing this:
它也应该这样做:
$myvar = "123";
include ("my.php");
....
echo $GLOBALS["myvar"];
Have a nice day.
祝你今天过得愉快。
回答by Jeremy1026
In regards to the OP's question, specifically "The variable needs to be set and evaluated from the calling first file (it's actually '$_SERVER['PHP_SELF']', and needs to return the path of that file, not the included second.php)."
关于 OP 的问题,特别是“需要从调用的第一个文件中设置和评估变量(它实际上是 '$_SERVER['PHP_SELF']',并且需要返回该文件的路径,而不是包含的第二个文件。 php)”。
This will tell you what file included the file. Place this in the included file.
这将告诉您包含该文件的文件。将其放在包含的文件中。
$includer = debug_backtrace();
echo $includer[0]['file'];
回答by Brian Kosnoff
I've run into this issue where I had a file that sets variables based on the GET parameters. And that file could not updated because it worked correctly on another part of a large content management system. Yet I wanted to run that code via an include file without the parameters actually being in the URL string. The simple solution is you can set the GET variables in first file as you would any other variable.
我遇到了这个问题,我有一个基于 GET 参数设置变量的文件。并且该文件无法更新,因为它在大型内容管理系统的另一部分正常工作。然而,我想通过包含文件运行该代码,而参数实际上不在 URL 字符串中。简单的解决方案是您可以像设置任何其他变量一样在第一个文件中设置 GET 变量。
Instead of:
代替:
include "myfile.php?var=apple";
It would be:
这将是:
$_GET['var'] = 'apple';
include "myfile.php";
回答by DrOne
OPTION 1worked for me, in PHP 7, and for sure it does in PHP 5 too. And the global scope declaration is not necessary for the included file for variables access, the included - or "required" - files are part of the script, only be sure you make the "include" AFTER the variable declaration. Maybe you have some misconfiguration with variables global scope in your PHP.ini?
选项 1在 PHP 7 中对我有用,当然在 PHP 5 中也适用。并且全局范围声明对于变量访问的包含文件不是必需的,包含 - 或“必需” - 文件是脚本的一部分,只需确保在变量声明之后进行“包含”。也许您的 PHP.ini 中的变量全局范围存在一些错误配置?
Try in first file:
在第一个文件中尝试:
<?php
$myvariable="from first file";
include ("./mysecondfile.php"); // in same folder as first file LOLL
?>
mysecondfile.php
我的第二个文件
<?php
echo "this is my variable ". $myvariable;
?>
It should work... if it doesn't just try to reinstall PHP.
它应该可以工作...如果它不只是尝试重新安装 PHP。
回答by Jim
According to php docs (see $_SERVER) $_SERVER['PHP_SELF'] is the "filename of the currently executing script".
根据 php 文档(参见$_SERVER) $_SERVER['PHP_SELF'] 是“当前正在执行的脚本的文件名”。
The INCLUDE statement "includes and evaluates the specified" file and "the code it contains inherits the variable scope of the line on which the include occurs" (see INCLUDE).
INCLUDE 语句“包含并评估指定的”文件,“它包含的代码继承了包含发生所在行的变量范围”(请参阅INCLUDE)。
I believe $_SERVER['PHP_SELF'] will return the filename of the 1st file, even when used by code in the 'second.php'.
我相信 $_SERVER['PHP_SELF'] 将返回第一个文件的文件名,即使在“second.php”中的代码使用时也是如此。
I tested this with the following code and it works as expected ($phpSelf is the name of the first file).
我使用以下代码对此进行了测试,它按预期工作($phpSelf 是第一个文件的名称)。
// In the first.php file
// get the value of $_SERVER['PHP_SELF'] for the 1st file
$phpSelf = $_SERVER['PHP_SELF'];
// include the second file
// This slurps in the contents of second.php
include_once('second.php');
// execute $phpSelf = $_SERVER['PHP_SELF']; in the secod.php file
// echo the value of $_SERVER['PHP_SELF'] of fist file
echo $phpSelf; // This echos the name of the First.php file.
回答by Leonardo Borsten
I found that the include parameter needs to be the entirefile path, not a relative path or partial path for this to work.
我发现 include 参数需要是整个文件路径,而不是相对路径或部分路径才能工作。
回答by Nicolas
This worked for me: To wrap the contents of the second file into a function, as follows:
这对我有用:将第二个文件的内容包装成一个函数,如下所示:
firstFile.php
第一个文件.php
<?php
include("secondFile.php");
echoFunction("message");
secondFile.php
第二个文件
<?php
function echoFunction($variable)
{
echo $variable;
}

