问题描述
当包含()和required_once()的另一个php文件中包含一个php文件时,我很难找到一种将php文件正确加载到另一个php文件中的方法.我发现如果当Afile.php包含在另一个目录中的Bfile.php中时,Afile.php使用诸如 ../controller/mycontroller.php
之类的URL来包含另一个php文件. ../
会将Afile.php的网址引导至基于Bfile.php的其他目录.
I have trouble to find a way to load a php file correctly in another php file when the php file is included in another php file with include () and required_once(). I found that ifAfile.php uses url such as ../controller/mycontroller.php
to include another php file in it, when Afile.php in been included in Bfile.php which is located in a different dir, the ../
will lead the Afile.php's url to a different dir that is based on Bfile.php.
我试图使用这些PHP字符串来指定一个带有静态URL的文件的url,这样,当许多.php文件中包含多个include时,就不会造成误解.但这没用!
I tried to use these PHP string to specify a file's url with a static one, so that there is no misunderstanding when there is multiple include among many .php files. But it did not work!
是否有更好的方法来定义.php文件的文件位置,以便当我要包含,调用或加载位于其他目录中的.php文件时,本身也包含在其他php文件中.目录?
Is there a better way to define a file location of a .php file so that when I want to include, call or load the .php file that is in a different dir while itself is also included in other php file in other dir?
如果有任何困惑,请告诉我.
If there is any confusion please let me know.
谢谢
更新
define('PUBLICPATH', __DIR__.'/');
// I prefer to have the "root dir" not accessible from public dir
define('ROOTROOT', realpath(PUBLICPATH.'..').'/');
$pathnow= define('APPPATH', realpath(PUBLICPATH.'../application').'/');
echo 'pathnow:'.APPPATH;
它返回 pathnow:/
作为chrome中的结果页面
It returned pathnow:/
as result page in chrome
推荐答案
最简单的方法是在第一个调用脚本中定义一个常量 ROOT_PATH
(或更多),然后在每个include中使用它/require指令.例如,假设您有以下树:
The easiest thing is to define one constant ROOT_PATH
(or more) in the first called script, then to use it in every include/require instruction. For example let's say you have the following tree:
/var/www/example.com -
/var/www/example.com/www - your public directory, accessible from www.example.com
/var/www/example.com/application -
index.php
index.php
<?php
// for recent php version, __DIR__ just do it
define('PUBLICPATH', __DIR__.DIRECTORY_SEPARATOR);
// in case __DIR__ is not available use the following:
// define('PUBLICPATH', dirname(__FILE__).DIRECTORY_SEPARATOR);
// I prefer to have the "root dir" not accessible from public dir
define('ROOTROOT', realpath(PUBLICPATH.'..').DIRECTORY_SEPARATOR);
define('APPPATH', realpath(PUBLICPATH.'..'.DIRECTORY_SEPARATOR.'application').DIRECTORY_SEPARATOR);
require(APPPATH.'bootstrap.php');
对于类定义,您还可以使用自动加载器(带有__autoload或spl_autoload_register)来加载类,而不必之前包含/需要它们的文件.
For classes definitions, you can also use an autoloader (with __autoload or spl_autoload_register ) to load classes without having to include/require their file before.
我用 DIRECTORY_SEPARATOR
替换了'/'
,以使其在窗口和unix上均可使用.
I replaced '/'
by DIRECTORY_SEPARATOR
to make it work on both window and unix.
这篇关于如何在另一个PHP文件中正确加载一个PHP文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!