将变量从一个 php 包含文件传递到另一个:全局与非 [英] Passing a variable from one php include file to another: global vs. not

查看:24
本文介绍了将变量从一个 php 包含文件传递到另一个:全局与非的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将一个变量从一个包含文件传递到另一个.这不起作用,除非我在第二个包含文件中将该变量声明为全局变量.但是,我不需要在调用第一个包含的文件中将其声明为全局.例如:

I'm trying to pass a variable from one include file to another. This is NOT working unless I declare the variable as global in the second include file. However, I do NOT need to declare it as global in the file that is calling the first include. For example:

front.inc:

$name = 'james';

<小时>

index.php:


index.php:

include('front.inc');
echo $name;
include('end.inc');

输出:詹姆斯

end.inc:

echo $name;

输出:无

如果我在 end.inc 中回显 $name 之前声明全局 $name,那么它可以正常工作.这篇文章的公认答案解释说,这取决于您的服务器配置:将 PHP 中的变量从一个文件传递到另一个文件

IF I declare global $name prior to echoing $name in end.inc, then it works properly. The accepted answer to this post explains that this depends on your server configuration: Passing variables in PHP from one file to another

我使用的是 Apache 服务器.我将如何配置它以便不需要将 $name 声明为全局?一个和另一个有什么优点/缺点吗?

I'm using an Apache server. How would I configure it so that declaring $name to be global is not necessary? Are there advantages/disadvantages to one vs. the other?

推荐答案

父文件可以访问两个包含文件中的变量

在 PHP 中包含文件时,它的行为就像代码存在于包含它们的文件中一样.想象一下,将每个包含文件中的代码直接复制并粘贴到 index.php 中.这就是 PHP 使用包含的方式.

The parent file has access to variables in both included files

When including files in PHP, it acts like the code exists within the file they are being included from. Imagine copy and pasting the code from within each of your included files directly into your index.php. That is how PHP works with includes.

因此,在您的示例中,由于您在 front.inc 文件中设置了一个名为 $name 的变量,然后同时包含了 front.incend.inc 在您的 index.php 中,您将能够 echo 变量 $nameindex.phpfront.incinclude 之后的任何位置.同样,PHP 会处理您的 index.php,就好像您包含的两个文件中的代码是文件的部分.

So, in your example, since you've set a variable called $name in your front.inc file, and then included both front.inc and end.inc in your index.php, you will be able to echo the variable $name anywhere after the include of front.inc within your index.php. Again, PHP processes your index.php as if the code from the two files you are including are part of the file.

当您将 echo 放入包含文件中时,将其放置到未在其自身中定义的变量时,您将不会得到结果,因为它与任何其他包含文件分开处理.

When you place an echo within an included file, to a variable that is not defined within itself, you're not going to get a result because it is treated separately then any other included file.

换句话说,要执行您期望的行为,您需要将其定义为全局.

In other words, to do the behavior you're expecting, you will need to define it as a global.

这篇关于将变量从一个 php 包含文件传递到另一个:全局与非的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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