定义我自己的 BASE_PATH 与 set_include_path?
我了解了函数set_include_path()。一直以来,我在 config.php 文件中定义了一个常量
define('BASE_PATH', '/var/www/mywebsite/public_html/');
,并且在所有后续的 php 文件中,我都会像这样包含
include(BASE_PATH.'header.php');
include(BASE_PATH.'class/cls.data_access_object.php');
常量方法与 set_include_path 方法相比是否有任何优势,反之亦然?持续的方法已经过时了吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 set_include_path() (或 ini_set('include_path', ...)) 允许您指定包含库代码的多个文件夹。例如,如果您的应用程序依赖于各种不同的框架/库,例如 PEAR 和 Zend FW,您可能会使用
ini_set('include_path', '/usr/local/php/pear:/usr/local/php /zendfw');
这种方法的缺点是它将使用它首先找到的任何文件;如果您的多个包含路径中有一个名为“Mailer.php”的文件,它将包含它找到的第一个文件,如果这不是您的意图,则会导致微妙的错误。良好的代码组织通常可以解决该问题。此外,include_path 会遍历真实路径缓存 (https://www.php.net/realpath),有时需要根据您的设置进行调整以获得更好的性能。
两种方法都可以,但是使用 Define() 方法更明确。
FWIW,我通常使用 ini_set('include_path', ...)。
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 (https://www.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', ...).
我认为米迦勒的解释非常清楚。
当您将所有 PHP 文件存储在文件夹中时,我建议您使用“set_include_path”,例如:“libs/”(更容易)。
当您显式指定文件路径时,使用 Define() 方法应该会更快。
除非确实有必要,否则始终尽量避免使用绝对路径。
我发现以这种方式指定路径非常有用:
这样您就可以避免每次移动代码时都必须更新路径。
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:
This way you will avoid to have to update the path each time you move the code.