有没有一种方法可以在php include中使用另一个文件中的变量? [英] Is there a way to use a variable from another file in a php include?
问题描述
所以基本上我有一个文件,可以说file1.php
,它包含另一个file2.php
.
So basically I have a file, lets say file1.php
and it includes another file2.php
.
file1.php
包含一个名为$dateString
的变量,我对该变量进行了一些操作.
file1.php
contains a variable called $dateString
that I have performed some operations on.
file2.php
也具有称为$dateString
的相同变量,但是即使$dateString
在包含file2.php
之前已初始化,此包含文件中也未引用此变量.
file2.php
also has the same variable called $dateString
however this variable is not being referenced within this include file even though $dateString
was initialized prior to including file2.php
.
因此,当前是file1.php
的样子:
$dateString = 'some expression';
include 'file2.php';
file2.php
基本上是试图回显在file1.php
file2.php
is basically trying to echo out the variable that was initialized in file1.php
echo $dateString;
除了一个变量之外,file2.php
中的所有其他内容都被正确调用了.
Everything else from file2.php
is being called properly except that one variable.
希望这是有道理的.这在PHP中可行吗?我在其他地方已经读到了需要全局设置变量的信息,其他地方提到了如何无法从子文件中的父文件引用变量..有什么想法吗?预先感谢!
Hopefully this makes sense. Is this possible in PHP? I have read in other places that you need to make the variables global and others have mentioned how you cant reference a variable from a parent file within a child file..any thoughts? Thanks in advance!
推荐答案
当您使用PHP的include()
时,没有任何神奇的事情发生.所包含文件的代码基本上只是插入到包含该文件的位置,这会导致一个更大的PHP文件.
父"文件还是子"文件并不重要-这是很重要的位置,因为PHP将从顶部到底部解析单个结果文件.
there is nothing magically happening when you use PHP's include()
. the included file's code is basically just inserted at the point where you are including it - resulting in one bigger PHP file.
it doesn't really matter if the "parent" or in the "child" file - it's the position that matters since PHP will parse the single resulting file from top to bottom.
例如:如果在包含文件B之前在文件A中设置了变量,则文件B将知道该变量.但是,如果您在包含文件B之后在文件A中设置了变量-文件B不知道该变量.
for example: if you set the variable in file A before including file B, file B will know about the variable. but if you set the variable in file A after including file B - file B doesn't know it.
这篇关于有没有一种方法可以在php include中使用另一个文件中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!