简体   繁体   English

包含来自不同目录的文件

[英]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). 我的cart.php显示的页面包含一个由table.php(包含文件)生成的表。 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. 我为表分隔文件的原因是因为我必须在cart.php中执行某些操作后再次生成表 - 删除当前表并使用Ajax加载新表。 However, my table.php file has this line: 但是,我的table.php文件有这一行:

require_once("include/database.php");

This is quite problematic, since when the file is included from cart.php, the path makes sense. 这是非常有问题的,因为当cart.php中包含该文件时,该路径是有意义的。 But when it's called by itself, the current directory will be cart/ and there is no include directory in cart/. 但是当它自己被调用时,当前目录将是cart /并且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? 有可能告诉PHP包括/应该总是搜索文件,无论它在哪里被调用? 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: 在这种情况下,我建议在常量中定义应用程序的(绝对)根路径,例如,将其添加到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,则可以设置包含路径

.htaccess: 的.htaccess:

php_value include_path "/path/to/include/"

php file: php文件:

require_once get_include_path().'file.php';


Another way : 另一种方式

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

In table.php 在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. 好吧,重读你的问题,看起来你想要autoload ,但我们没有足够的信息来确定你的类是否以有利于自动加载的方式设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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