define my own BASE_PATH vs. set_include_path?

落爺英雄遲暮 提交于 2019-12-05 22:43:58

问题


I learned of the function set_include_path(). All this time, I defined a constant in the config.php file

define('BASE_PATH', '/var/www/mywebsite/public_html/');

And in all subsequent php files, I would include like so

include(BASE_PATH.'header.php');
include(BASE_PATH.'class/cls.data_access_object.php');

Is there any advantage with the constant approach vs. the set_include_path approach and vice versa? Is the constant approach obsolete?


回答1:


Using set_include_path() (or ini_set('include_path', ...)) allows you to specify multiple folders that would contain your library code. For instance, if your application relies on a variety of different frameworks/libraries, e.g. PEAR and Zend FW, you might have something like,

ini_set('include_path', '/usr/local/php/pear:/usr/local/php/zendfw');

The disadvantage to that approach is that it will use whatever file it finds first; if you have a file called "Mailer.php" in more than one of your include paths, it will include the first one it finds, causing subtle bugs if that's not your intention. Good code organization typically resolves that issue. Also, include_path goes through the realpath cache (http://us2.php.net/realpath), which sometimes needs to be tweaked to get better performance depending on your setup.

Both ways are fine, however using the define() method is more explicit.

FWIW, I generally use ini_set('include_path', ...).




回答2:


I think Micahel's explanation is very clear.

I recommended you to use "set_include_path" when you store all your PHP files in an folder, for example: "libs/" (its easier). Using the define() method should be faster as you are specifying the file path explicitly.

Always try to avoid to use absolute paths unless they are really necessary. I found very useful to specify your paths this way:

define("BASE_PATH", dirname(__FILE__));

This way you will avoid to have to update the path each time you move the code.



来源:https://stackoverflow.com/questions/1787661/define-my-own-base-path-vs-set-include-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!