php require include

Its quite common to see such lines :

require_once('../../lib/some_class.php');

This approach has many drawbacks :

It first searches for directories specified in the include paths of php , then looks from the current directory.
So many directories are checked.

When a script is included by another script in a different directory , its base directory changes to that of the including script.

Another issue , is that when a script is being run from cron , it may not have its parent directory as the working directory.

So its a good idea to have absolute paths :

define('ROOT' , '/var/www/project/');
require_once(ROOT . '../../lib/some_class.php');

//rest of the code

Now this is an absolute path and will always stay constant. But we can improve this further. The directory /var/www/project can change , so do we change it everytime ? No instead we make it portable using magic constants like __FILE__ . Take a closer look :

//suppose your script is /var/www/project/index.php
//Then __FILE__ will always have that full path.

define('ROOT' , pathinfo(__FILE__, PATHINFO_DIRNAME));
require_once(ROOT . '../../lib/some_class.php');

//rest of the code

So now even if you shift your project to a different directory , like moving it to an online server , the same code will run without any changes.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章