将变量从一个php包含文件传递到另一个:global与not

编程入门 行业动态 更新时间:2024-10-27 14:28:32
本文介绍了将变量从一个php包含文件传递到另一个:global与not的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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:

front.inc:

$name = 'james';

index.php:

index.php:

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

输出:james

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使用包含的方式。

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.

因此,在您的示例中,因为您设置了一个名为 $ name 在你的 front.inc 文件中,然后包括 front.inc 和结束.inc 在您的 index.php 中,您将能够 echo 变量 $ name 在你的包含 前面的任何地方 的index.php 。再次,PHP处理您的 index.php ,就好像您所包含的两个文件中的代码是文件的 part 一样。

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包含文件传递到另一个:global与not

本文发布于:2023-07-25 12:13:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1209773.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   文件   php   global

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!