问题
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 if
Afile.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.
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!
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.
Thank You
Update
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;
It returned pathnow:/
as result page in chrome
回答1:
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
<?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');
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.
EDIT: I replaced '/'
by DIRECTORY_SEPARATOR
to make it work on both window and unix.
来源:https://stackoverflow.com/questions/20194875/how-to-correctly-load-a-php-file-in-another-php-file