PHP 自动加载和 set_include_paths
我有一个使用几个不同类的小应用程序。在每个文件中,我设置相关文件夹的包含路径并声明自动加载功能。
这工作正常,但必须有更好的方法来执行此操作,因为我必须对每个文件执行此操作。
有没有办法一次性执行此操作,而不必为每个页面加载执行此操作。
如果这是一个愚蠢的问题,请原谅我,但我是 php 的新手,真的只是想从一开始就以最好的方式做事。
感谢任何可以提供帮助的人。
I have a small app that uses a few different clases. In each file i am setting the include paths to the relevant folders and declaring an autoload function.
This works fine but there must be a better way to do this as I have to do this on every file.
Is there a way to do this once instead of having to do it for every single page load.
Please excuse me if this is a silly question but I am new to php and really just want to do things the best way from start.
Thank you to anyone that can help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 autoload.php 中定义您需要的所有脚本通用的所有内容,然后从每个脚本加载它?
Define everything you need and is common for all scripts in autoload.php, and load it from each script?
我建议制作一个包含标准类、设置任何标准常量、路径、清理 GET/POST 等的单个脚本文件。然后在每个文件的开头包含一次。可能会有例外,但 90% 以上的情况都是如此。
另外,查看 __autoload。这可能是处理此问题的更复杂的解决方案。
I'd suggest making a single script file that includes the standard classes, sets any standard constants, paths, sanitize GET/POST, etc. Then include that once at the beginning of each file. You may have exceptions, but it will be handly 90%+ of the time.
Also, look into __autoload. It may be the more sophisticated solution to handle this.
尝试在您的index.php中编写 __autoload() 函数(我假设它是您网站的入口点)。这应该使自动加载可用于此后调用的所有脚本。这就是我维护在 Zend 上运行的网站的方式。
Try to write the __autoload() function in your index.php (which I am assuming is the entry point to your website). This should make autoload available to all scripts invoked thereafter. This is how I am maintaining my website which is running on Zend.
执行此操作的最佳方法取决于应用程序的组织方式。如果您的应用程序只是脚本的集合,那么最好的方法是简单地在脚本中重载 _autoload() 函数,然后将该脚本包含在每个文件的顶部。示例:
shared.php
script1.php
另一种方法是最好的方法。我建议使用某种 MVC 框架或编写您自己的基本 MVC。这会让事情变得容易很多。 MVC 框架允许您拥有一个公共入口点。这在这种情况下很有用,因为您可以非常轻松地在入口点覆盖 _autoload() 函数,并且它将在整个应用程序中生效。这样,每次创建类时,您都可以浏览所有预定义的目录以找到要包含的正确文件。
The best method for doing this depends on how your application is organized. If your app is just a collection of scripts, then the best way would be to simply overload the _autoload() function in a script and then include that script at the top of each file. Example:
shared.php
script1.php
The other way of doing this is the best way. I would suggest using an MVC framework of some kind or writing your own basic MVC. This would make things a lot easier. An MVC framework allows you to have a common entry point. This is helpful at times like these because you can very easily overwrite the _autoload() function at the entry point, and it will take effect throughout your application. That way, each time a class is created, you can look through all of your predefined directories to find the correct file to include.