PHP:使用绝对路径在include / require文件中定义的变量不可访问 [英] PHP: Variable not accessible defined in include/require file using absolute path
问题描述
我发现难以访问包含文件中定义的变量。
I am finding difficulty in accessing a variable defined in the include file.
我的包含文件存在于根目录中,它有一个变量 $ x
:
My include file is present in the root and it has a variable $x
:
localhost / dir_name / include.php
我在 file.php
目前包括 include.php
文件在子目录中:
I am including the include.php
file in file.php
present in the sub directory :
localhost / dir_name / sub_directory / file.php
但每次,file.php都会给出错误未定义变量$ x
But every time, the file.php gives the error of undefined variable $x
奇怪的是,当我使用相对路径来包含 include.php
时,它完美无缺。像这样:
The weird thing is that when I use a relative path to include the include.php
, it works perfectly. Like this:
包括'../ include.php';
此外,它在使用 realpath($ _ SERVER ['DOCUMENT_ROOT'])
时有效。像这样:
ALSO, it works when using realpath($_SERVER['DOCUMENT_ROOT'])
. Like this:
包括$ _SERVER ['DOCUMENT_ROOT']。'\dir_name \include.php'
但它永远不会适用于绝对路径。我也尝试将变量设为全局但没有帮助我,并且 include.php
文件也正确包含在内。除了这个未定义的变量之外,它没有给我任何其他错误。
But it never works for the absolute path. I also tried making the variable global but didn't helped me and the include.php
file is also included correctly. It is not giving me any other error except this undefined variable.
在询问之前,我尝试在SO上找到它,但找不到这个错误的答案。
Before asking, I tried finding this on SO, but couldn't find the answer to this error.
我目前正在使用 realpath($ _ SERVER [DOCUMENT_ROOT])
作为替代方案。
I am currently using the realpath($_SERVER["DOCUMENT_ROOT"])
as an alternative.
推荐答案
localhost
不是绝对路径。 PHP读取计算机上的实际目录,而不是URL中的目录。
localhost
is not an absolute path. PHP reads the actual directories on your computer, not the ones from the URL.
尝试 echo realpath($ _ SERVER [DOCUMENT_ROOT])
你会明白我的意思。
Try echo realpath($_SERVER["DOCUMENT_ROOT"])
and you'll see what I mean.
这篇关于PHP:使用绝对路径在include / require文件中定义的变量不可访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!