In general the include
, like the require
work like this:
If the files are in the same directory as the script
include ("archivo.php");
If the files are in another directory
If the file is in the parent directory of the script, ../
is set in front of the file name:
include ("../archivo.php");
../
is used to backtrack between directories.
You can also use $_SERVER['DOCUMENT_ROOT']
as a reference point.
If config.php
is in the root directory. You could make a include
of this file from WorkerImp.php
by:
include($_SERVER['DOCUMENT_ROOT']."/config.php");
Or by:
include("../../config.php");
here ../../
goes back two directories from where the script is located. That is, go back imp>dao>
searching config.php
in the directory found in the root of the App.
Another possibility
I have implemented the following, to stay independent of any possible change of route.
I have created a file called dirs.php
in which I have defined all the routes of my project. I put that file in the root (root directory).
<?php
define('ROOT_PATH', $_SERVER['DOCUMENT_ROOT'].'/');
define('CONTROLLER_PATH', ROOT_PATH.'controller/');
define('MODEL_PATH', ROOT_PATH.'model/');
define('DAO_PATH', ROOT_PATH.'dao/');
define('IMP_PATH', DAO_PATH.'imp/');
...
etc
?>
Then, when I need to include some project file:
include_once ($_SERVER['DOCUMENT_ROOT'].'/dirs.php');
include (DAO_PATH."PersonaDao.php");
Note that I use include_once
, so that you do not include it again if another file of the project has done it (to understand the difference between include
e include_once
you can consult: What is the difference between require, require_once, include, include_once in PHP?
What is the advantage of using this method?
If for some reason I have to change a path in the directory Dao
, I do not have to review all the parts where the include includes that directory, just change the value of DAO_PATH
and you're done.
What is the disadvantage?
By including the file dirs.php
you will be including some constants that you may not be using. Nor are hundreds or thousands of constants, so it will not affect the performance of your program.