简体   繁体   English

在PHP脚本中包括多个目录

[英]Include Multiple Directories in PHP script

How to include multiple paths when a PHP script is called? 调用PHP脚本时如何包含多个路径?

For example, I need to point include_path to multiple directories; 例如,我需要将include_path指向多个目录。 inside each directories containing sub directories etc. But I want to include all the php files inside the sub directories as well, so that when my master PHP script can call any methods and objects defined inside the directories. 在每个包含子目录等的目录中。但是我也想在子目录中包含所有php文件,以便当我的主PHP脚本可以调用目录中定义的任何方法和对象时。

Any idea? 任何想法?

If possible, I would like to call a function to do it, instead of specifying the root directories and loop through everything inside the directories. 如果可能的话,我想调用一个函数来执行此操作,而不是指定根目录并遍历目录内的所有内容。

You might be better off using spl_autoload_register() , to register a callback which PHP will call when it can't find a class you are trying to access. 使用spl_autoload_register()可能会更好,可以注册一个PHP找不到您要访问的类时将调用的回调。 You can then write a function to include the correct file based on the name. 然后,您可以编写一个函数来根据名称包含正确的文件。 Libraries like PEAR tend to do this by splitting the Class name by underscore, and each part corresponds to a directory in its path. 像PEAR这样的库通常通过用下划线将Class名称拆分来实现此目的,并且每个部分都对应于其路径中的目录。

I don't think there is any way that you can get PHP (when including a file) to recursively search the include path until it finds the file (unless you write this logic yourself - I suppose you could write wrappers around require(), include() etc., and call those instead, but I wouldn't). 我不认为有任何方法可以让PHP(包括文件时)递归搜索包含路径,直到找到文件为止(除非您自己编写此逻辑-我想您可以围绕require()编写包装, include()等,然后改为调用它们,但我不会)。

You could also recursively scan through the directories and add each one to the include path when your script starts, but I think this would make including subsequent files much slower. 您也可以递归地扫描目录,并在脚本启动时将每个目录添加到包含路径,但是我认为这会使包含后续文件的速度变慢。

It sounds like you want to specify each and every directory in your include_path to allow you to just do 听起来您想在include_path中指定每个目录,以便您可以

require_once("x.php"); // this is in ./foo/bar
require_once("y.php"); // this is in /docs/utils/
require_once("z.php"); // this is in /some/other/include/path

In which case, don't. 在这种情况下,请不要。 That idea is full of lose, and bad for documentation, debugging, and sanity. 这个想法充满了失败,并且不利于文档编写,调试和理智。

If you must, you'd have to write a function to recursively crawl your include directory by hand as part of a bootstrap process, or do it by hand. 如果必须的话,您必须编写一个函数来作为引导过程的一部分递归地手动爬取包含目录,或者手动执行。

Either way, this sounds like a bad idea and isn't a feature for a reason. 无论哪种方式,这听起来都是个坏主意,并不是有原因的功能。

您需要用分号分隔多个目录

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM