我习惯在php脚本中使用include()很多.我想知道这是一个好方法.我只是使用了很多,因为它使代码看起来更好,以便于面向未来的编程.
利用php自动加载功能
例:
function __autoload($class_name) {
include $class_name . '.php';
}
Run Code Online (Sandbox Code Playgroud)
每当你实例化一个新类时.PHP使用一个参数(即类名)自动调用__autoload函数.考虑下面的例子
$user = new User():
Run Code Online (Sandbox Code Playgroud)
当您在此处实例化用户对象时,将调用自动加载功能,它会尝试包含来自同一目录的文件.(参考上述自动加载功能).现在你可以实现自己的逻辑来自动加载类.无论它驻留在哪个目录中.有关更多信息,请访问此链接http://in.php.net/autoload.
更新: @RepWhoringPeeHaa,你说它是正确的伙伴.使用spl_autoload然后使用简单的自动加载功能有更多好处.我看到的主要好处是可以使用或注册多个功能.
例如
function autoload_component($class_name)
{
$file = 'component/' . $class_name . '.php';
if (file_exists($file)) {
include_once($file);
}
}
function autoload_sample($class_name)
{
$file = 'sample/' . $class_name . '.php';
if (file_exists($file)) {
include_once($file);
}
}
spl_autoload_register('autoload_component');
spl_autoload_register('autoload_sample');
Run Code Online (Sandbox Code Playgroud)
如果您正在开发面向对象并为每个类创建一个文件,请考虑实现一个自动加载器函数,该函数include在使用类但尚未加载时自动调用:
$callback = function($className) {
// Generate the class file name using the directory of this initial file
$fileName = dirname(__FILE__) . '/' . $className . '.php';
if (file_exists($fileName)) {
require_once($fileName);
return;
}
};
spl_autoload_register($callback);
Run Code Online (Sandbox Code Playgroud)