开发者

How to get these PHP includes working?

开发者 https://www.devze.com 2023-03-10 20:06 出处:网络
I\'ve got the following file structure: / +--- inc/ |+--- lib1.php +--- inc2/ |+--- lib2.php |+--- view2.php

I've got the following file structure:

/
+--- inc/
|    +--- lib1.php
+--- inc2/
|    +--- lib2.php
|    +--- view2.php
+--- view1.php

Both view1.php and view2.php in开发者_StackOverflowclude lib2.php. Lib2.php includes lib1.php. Graphically:

View1.php ---\
             +---> Lib2.php ---> Lib1.php
View2.php ---/

However I cannot get this working, because the search paths are wonky. If I try to include "../lib1.php" then only view2.php works. If I try to include "inc/lib1.php", then only view1.php works. The other view always complains about file not found.

What should be the correct way of handling this?


If you use php >= 5.3 you can use __DIR__ to build the path. If not, use dirname(__FILE__) So in lib2.php, just put this:

require_once(__DIR__ . '../inc/lib1.php');


In your user facing files, define a constant like so (assuming PHP 5.3 here):

<?php
define('ROOT_INCLUDE_PATH', __DIR__ . '/');

Now, in any file within your project that is included by your user facing files, you just use a simple include.

This next snippet would be view1.php:

<?php
define('ROOT_INCLUDE_PATH', __DIR__ . '/');
// ...
include ROOT_INCLUDE_PATH . 'inc/lib1.php';
include ROOT_INCLUDE_PATH . 'inc2/lib2.php';

And this would be view2.php (note that we use dirname() here to make the root path up a directory):

<?php
define('ROOT_INCLUDE_PATH', dirname(__DIR__) . '/');
// ...
include ROOT_INCLUDE_PATH . 'inc/lib1.php';
include ROOT_INCLUDE_PATH . 'inc2/lib2.php';

This means that your includes can include other includes without any modifications at all; so long as you define the root include path appropriately in your user-facing files, it's all good.


Since relying on a relative path won't work, I think that a possible solution is to use an absolute path. Declare $system_path = "/" as a global variable, so you can always include based on the system path.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号