在PHP类文件中的何处放置include语句

Svi*_*ish 5 php class include

在PHP类文件中包含文件最明智的地方是什么?例如,如果其中一个方法需要一个外部类,那么我应该在该方法中使用的位置包含文件,还是应该在该类之前完成?还是在构造函数中?要么?你有什么建议吗?优点?缺点?还是真的只是口味问题?

include_once 'bar.class.php';
class Foo
{
    public static function DoIt()
    {
        new Bar();
    }
}
Run Code Online (Sandbox Code Playgroud)

class Foo
{
    public static function DoIt()
    {
        include_once 'bar.class.php';
        new Bar();
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 4

我更喜欢它在上面,与 c / java/c# 中的#import//相同的约定,因为它可以立即让您知道您的类依赖于哪些其他类。importusing

您可能还想签出require_once()而不是因为include_once()当包含的文件包含错误时它会因错误而停止而不是发出警告。但这当然取决于您要包含的文件类型以及您认为它的重要性。