调用其他类方法的类方法没有include / require?

时间:2010-08-06 02:40:31

标签: php zend-framework

我不知道如何在搜索引擎中说出这个问题。

我有点混淆了类如何在没有include / require的情况下使用其他类的方法。我已经在PHP中看到过这几次了。来自C ++背景,我必须包含所有内容才能使用它,所以它有点令人困惑。

但好的,我们走了:

说我有improve_db_connection.php

class improve_db_connection
{

    protected $_connection;

    public function __construct($host, $user, $pwd, $db)
    {
        $this->_connection = @new mysqli($host, $user, $pwd, $db);
        if (mysqli_connect_error()) {
            throw new RuntimeException('Cannot access database: ' .
                mysqli_connect_error());
        }
    }

    public function getResultSet($sql)
    {
        $results = new Pos_MysqlImprovedResult($sql, $this->_connection);
        return $results;
    }
}

new Pos_MysqlImprovedResultPos_MysqlImprovedResult类的实例,而不是improve_db_connection。在没有声明include函数包含类Pos_MysqlImproveResult的情况下,improve_db_connection.php文件只知道类的位置。

是因为Pos_MysqlImproveResult.phpimprove_db_connection.php位于同一目录中吗?

Zend Framework也是如此。但是文件是在子目录等。我在application/modules/SF/models中有一个类,它使用application/modules/SF/models/resources中的另一个类函数。是因为这些类的Zend命名约定Zend只是解析这些文件并将其添加到php __autoload中?

2 个答案:

答案 0 :(得分:2)

为了增加Valorin的解释,PHP中有一种神奇的方法,当它无法找到类定义时,它会尝试查找类定义。有关详细说明,请转到此处: http://php.net/manual/en/language.oop5.autoload.php

这个要点是:

function __autoload ($class_name) {
    // write your logic to find the class name

    // iterate over the available paths
    foreach(explode(PATH_SEPARATOR, get_include_path()) as $path) {
        // create a local variable representing the file path to the would be include file
        $file = implode(DIRECTORY_SEPARATOR, array(
            $path, "{$class_name}.class.inc",
        ));

        // If the file doesn't exist, continue, avoiding further processing
        if (!file_exists($file)) { continue; }

        // require the file, and return to avoid further processing
        require_once $file;
        return;
    }
}

// provided there's a foo.class.inc file in one of your paths ...
$Foo = new Foo;

答案 1 :(得分:1)

Zend Framework使用Zend_Loader在引用类时自动加载类,只要它可以在逻辑位置找到它们。

我假设您正在运行基于Zend应用程序的脚本,该脚本会自动为您配置Autoloader并完成所有艰苦工作。由于您的文件位于其逻辑文件夹中,并且这些类具有ZF约定名称,因此ZF将在您引用它们时找到它们并加载它们。

更多信息请参阅ZF手册:
http://framework.zend.com/manual/en/zend.loader.html
http://framework.zend.com/manual/en/zend.application.html