PHP传递变量以包含 [英] PHP pass variable to include

查看:111
本文介绍了PHP传递变量以包含的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将一个变量传递给 include 文件。我的主机改变了PHP版本,现在我尝试的任何解决方案都无法正常工作。



我想我已经尝试了所有可以找到的选项。我确信这是最简单的事情!



变量需要从调用的第一个文件中设置和计算(它实际上是 $ _ SERVER ['' PHP_SELF'] ,并且需要返回该文件的路径,而不是包含的 second.php )。



OPTION ONE



在第一个文件中:

  global $ variable; 
$ variable =apple;
include('second.php');

在第二个文件中:

  echo $ variable; 

方式2

在第一个文件中:

 函数passvariable(){
$ variable =apple;
返回$ variable;
}
passvariable();

选项三

  $ variable =apple; 
包含myfile.php?var = $ variable; //我也尝试使用http:以及完整的站点地址。


$ variable = $ _GET [var]
echo $ variable

这些都不适合我。 PHP版本是5.2.16。



我缺少什么?



谢谢!

解决方案

选项3是不可能的 - 您会得到.php文件的呈现输出,就像您在浏览器中打开该网址一样。如果您获得了原始的PHP代码(如您所愿),那么您的网站的所有源代码都将被公开,这通常不是一件好事。



选项2没有多大意义 - 你会隐藏一个函数中的变量,并受PHP的变量作用域。你还必须有 $ var = passvariable()来将'inside'变量赋值给'outside',并且你又回到了原点。 / p>

选项1是最实用的。 include()基本上会在指定的文件中徘徊,并在那里执行,就好像文件中的代码实际上是父页面的一部分一样。它看起来像一个全局变量,这是大多数人在这里所不喜欢的,但通过PHP的解析语义,这两个是相同的:

  $ x ='foo'; 
包含('bar.php');

  $ x ='foo'; 
// bar.php的内容粘贴在这里


I'm trying to pass a variable into an include file. My host changed PHP version and now whatever solution I try doesn't work.

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).

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.

What am I missing?

Thanks!

解决方案

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.

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.

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:

$x = 'foo';
include('bar.php');

and

$x = 'foo';
// contents of bar.php pasted here

这篇关于PHP传递变量以包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆