Ali Bassam
Ali Bassam

Reputation: 9969

Unified path to require a file in PHP from all folders

I have the current tree.

/edu/index.php
/edu/Classes/Connection.php
/edu/Classes/User.php
/edu/Handlers/Post.php

When I need to use functions from Connection.php and User.php inside index.php, I require them using:

require_once './Classes/Connection.php';
require_once './Classes/User.php';

But some functions from User.php also needs functions from Connection.php to work, so since index.php is where the requests come from, I require Connection.php inside User.php using:

require_once './Classes/Connection.php';

But sometimes I need to use the same functions from Post.php, so

require_once './Classes/Connection.php'; inside User.php does not work if Post.php is the file sending requests.

Isn't there a unified path or solution so that I can be able to require the file from any place inside my project in the same way? I would really like to avoid a solution such as...

public function UserFunction($path){
  require_once $path;
}

And change the parameter on each call depending on my position inside the project folder.

Upvotes: 0

Views: 146

Answers (2)

Jonathan Kuhn
Jonathan Kuhn

Reputation: 15311

If the files you are trying to include are mostly classes, it would probably be best to implement the __autoload function. When you instantiate a class, if the class hasn't been defined, then the __autoload method is called with the class name so you can include the file. If you create a simple standard, like all classes reside in the $_SERVER['DOCUMENT_ROOT'].'/classes/' folder and the filename is the same as the class name like ClassName.php, you can dynamically load in any classes as they are needed.

Also, generally looked down upon but I figured I would mention it because I hadn't seen it offered yet. There is the set_include_path() function you can call that will allow you to set the path(s) that php looks when including a file. HOWEVER, this can cause some trouble. As an example, my work hosts several sites under sub-domains each with their own document root. Under the document root each site has its own "includes" folder. Well some genius about 8 years ago set the include path in the global apache config to /var/www/site1/includes;/var/www/site2/includes...etc. Problem is that when a file exists with the same name in site1 as site2 and you try to include it, you will always include the file from site1 because php will find the file there and stop looking. It has caused some small headaches from time to time.

Upvotes: 1

Orangepill
Orangepill

Reputation: 24655

Your best best is to include relative to __DIR__ to get a file relative to another file.

Other good points that you can include from are

$_SERVER["DOCUMENT_ROOT"]

or make your own using htaccess.

in .htaccess put

SetEnv MY_INCLUDE_PATH "/path/to/my/php/files";

then in php

include ($_SERVER["MY_INCLUDE_PATH"]."/Connection.php");

Upvotes: 1

Related Questions