我的主类定义如下:
class Admin {
private $theme_name;
function __construct($theme_name) {
$this->theme_name = $theme_name;
$this->init();
}
private function init(){
// load the framework files
}
}
实例化这个类将加载所有单独的模块类,并实例化它们。
我的问题是,我是否应该在init方法中包含必要的文件,比如:
private function init(){
// load the framework files
require_once ( 'interface.php' );
require_once ( 'uploader.php' );
//etc ..
$interface = new Interface(); //etc..
}
或者,我应该像这样将它们包含在类声明之上吗:
require_once ( 'interface.php' );
require_once ( 'uploader.php' );
class Admin { //etc..
在类中包含依赖项的最佳方式是什么?
在您的情况下,因为所有Admin
实例都需要这些额外的文件,所以将这些require_once
语句拉到文件的顶部是有意义的。
话虽如此,如果你有一个类自动加载器,你可以清理更多的文件。您向spl_autoload_register()
注册了一个函数,该函数将在所需类尚未加载时调用;函数将查找并加载必要的源文件。
两者都很好,但第二个更好,它使代码更漂亮。
我建议将init()
方法更改为static
,因为这不是管理员的行为,并且避免每次要包含这些文件时都实例化admin Object。
它们都是一样的。不过,为了保持更好的代码清洁性,我会将它们包含在类之外,从技术上讲,每次调用函数时都会调用includes,但在这种情况下,它是init
,所以听起来可能只被调用一次。
自动加载!它的价格有点高(有很多字符串工作要做,这会增加负载),但如果你只需要几次,它应该能很好地完成的工作
http://www.sitepoint.com/autoloading-and-the-psr-0-standard/
您可以使用__autoload()函数只拉入需要调用的类。
<?php
function __autoload($class_name)
{
$filename = "../class/".$class_name."php";
if ( file_exists($filename) )
{
include_once $filename;
}
}
?>