简体   繁体   中英

Including Files from Different Directories

So I have these files:

/
|
+ include/
|   |
|   + database.php
|
+ cart/
|   |
|   + table.php
|
+ cart.php

My cart.php displays the page with a table that was generated by table.php (included file). The reason that I have a separated file for the table is because I have to generate the table again after some operations in cart.php — the current table is removed and a new one is loaded with Ajax. However, my table.php file has this line:

require_once("include/database.php");

This is quite problematic, since when the file is included from cart.php, the path makes sense. But when it's called by itself, the current directory will be cart/ and there is no include directory in cart/.

Is there any way to fix this problem? I'd like to avoid using the big absolute path. Is it possible to tell PHP that include/ should be always searched for files, no matter where it was called? It it is, where should I do that (in which file)?

In this case I would suggest defining the (absolute) root path of your application in a constant, for example, add this to your config/bootstrap:

// Absolute path to your application's root directory
define('APP_ROOT', '/var/www/vhosts/example.com/httpdocs');

Then you can just include using that constant, like:

require_once(APP_ROOT . '/include/database.php');

If you are using .htaccess, you can set include path :

.htaccess:

php_value include_path "/path/to/include/"

php file:

require_once get_include_path().'file.php';


Another way :

require_once($_SERVER['DOCUMENT_ROOT']."/include/database.php");

In table.php

require_once('../include/database.php');

Well, rereading your question, it looks like you want to autoload things, but we don't have enough information to determine if your classes are set up in a way conducive to autoloading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM