Where to put include in a PHP class file

Where is the best place to include files in a PHP class file? For example, if one of the methods needs an external class, should I include a file where it is used in this method, or should it be executed before the class? Or in the constructor? Or? What do you recommend? Pros? Minuses? Or is it just a matter of taste really?

include_once 'bar.class.php'; class Foo { public static function DoIt() { new Bar(); } } 

vs

 class Foo { public static function DoIt() { include_once 'bar.class.php'; new Bar(); } } 
+4
source share
5 answers

I prefer it on top, this is the same convention as for #import / import / using in c / java / C #, as it immediately lets you know what other classes your class depends on.

You can also check require_once() instead of include_once() , as it will stop with an error instead of warning when the included file contains an error. But, of course, it depends on which file you include, and how critical you think it is.

+4
source

I would say that it depends.

So, if there is a rather large code base, and you would prefer that the code be loaded into memory every time there is a page request to a minimum, then I would only suggest including another php file when necessary.

However, if this script is always needed, then include it at the beginning of the script.

It really comes down to the situation and the requirements.

Hope this helps.

+1
source

It depends on the architecture used. Including files at the beginning is neat, but if this file prints text, then you cannot manipulate the headers, etc.

When you use MVC, the template controller must include class files.

+1
source

If you are sure that you need a file, do it on top. If you need files included on demand, you can view spl_autoload_register () to ease the pain.

0
source

It is always useful to include external files on top of the page. It will be very easy to find later. If the included file is very large, include it where you need it. See also the documentation for require_once and include_once .

There are also just require and include . Know the difference between them and which should be used when.

0
source

Source: https://habr.com/ru/post/1394856/


All Articles