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();
}
}
I prefer it on top, the same convention as for
#import/import/usingin 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 ofinclude_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.