Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to place include statements in a PHP class file

Tags:

include

php

class

Where is it wisest to include files in a PHP class file? For example if one of the methods needs a external class, should I include the file where it is used in that method, or should it be done before the class? Or in the constructor? Or? What do you recommend? Pros? Cons? 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();
    }
}
like image 877
Svish Avatar asked Feb 05 '12 12:02

Svish


Video Answer


3 Answers

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

You may also want to check out require_once() instead of include_once() as it will halt with an error instead of giving a warning when the included file contains an error. But of course that depends on what kind of file you're including and how critical you deem it to be.

like image 58
johangu Avatar answered Oct 29 '22 18:10

johangu


I would say that it depends.

So, if there is a rather large code base, and you would prefer to keep the code loaded into memory each time there is a page request down to a minimum, then I would suggest only including the other php file when needed.

However, if that script is always needed, then include it at the top of the script.

It really comes down to the situation and requirements.

Hope that helps.

like image 43
ralfe Avatar answered Oct 29 '22 16:10

ralfe


It depends on architecture you are using. Including files in the beginning is neat, but if that file prints text then you wont be able to manipulate headers etc.

When you are using MVC pattern controller should include class files.

like image 44
crossto Avatar answered Oct 29 '22 17:10

crossto