1

我对 OO 编程相当陌生...

我正在构建最终将成为整个网站使用的大型类库。显然,在每一页上加载整个库是浪费时间和精力......

所以我想做的是在每个页面上需要一个“config”php 类文件,并且能够根据需要“调用”或“加载”其他类——从而根据我的需要扩展我的类。

据我所知,由于范围问题,我不能使用配置类中的函数来简单地包含()其他文件。

我有哪些选择?开发者通常如何处理这个问题,什么是最稳定的?

4

2 回答 2

3

您可以使用__autoload()或创建一个对象工厂,该工厂将在您需要时加载所需的文件。

顺便说一句,如果您的库文件存在范围问题,您可能应该重构您的布局。大多数库都是可以在任何范围内实例化的类集。

以下是一个非常基本的对象工厂示例。

class ObjectFactory {

    protected $LibraryPath;

    function __construct($LibraryPath) {
        $this->LibraryPath = $LibraryPath;
    }

    public function NewObject($Name, $Parameters = array()) {
        if (!class_exists($Name) && !$this->LoadClass($Name))
            die('Library File `'.$this->LibraryPath.'/'.$Name.'.Class.php` not found.');
        return new $Name($this, $Parameters);
    }

    public function LoadClass($Name) {
        $File = $this->LibraryPath.'/'.$Name.'.Class.php'; // Make your own structure.
        if (file_exists($File))
                return include($File);
        else    return false;
    }
}

// All of your library files should have access to the factory
class LibraryFile {

    protected $Factory;

    function __construct(&$Factory, $Parameters) {
        $this->Factory = $Factory;
    }
}
于 2009-07-30T23:10:15.960 回答
2

如果您使用来自 3rd 方库的类,听起来您想要自动加载spl_autoload_register 。

于 2009-07-30T23:06:48.480 回答