7

我有在我的 php 脚本中大量使用 include() 的习惯。我想知道这是一个好方法。我只是经常使用 include,因为它使代码看起来更适合面向未来的编程。

4

3 回答 3

6

而不是使用 include 你可能想看看autoloading

于 2012-04-24T15:37:12.480 回答
5

利用php自动加载功能

例子:

function __autoload($class_name) {
    include $class_name . '.php';
}

每当您实例化一个新类时。PHP 使用一个参数即类名自动调用 __autoload 函数。考虑下面的例子

$user = new User():

当您在此处实例化用户对象时,会调用自动加载函数,它会尝试包含同一目录中的文件。(参考上面的自动加载功能)。现在您可以实现自己的逻辑来自动加载类。无论它驻留在哪个目录中。有关更多信息,请查看此链接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');
于 2012-04-24T15:38:23.993 回答
5

如果您正在开发面向对象并且每个类都有一个文件,请考虑实现一个自动加载函数,该函数会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);
于 2012-04-24T15:38:46.723 回答