2010-08-06 52 views
0

我不知道如何在搜索引擎中提出这个问题。调用其他类方法而不包含/需要的类方法?

我有点困惑如何使用其他类的方法没有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

回答

1

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

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

更多信息,在ZF手动:
http://framework.zend.com/manual/en/zend.loader.html
http://framework.zend.com/manual/en/zend.application.html

+0

如果它不是一个Zend的应用程序,那么它依然可以使用,这将在一个地方被定义自动加载磁带机脚本文件,并且可以读取它以确定在包括任何必要文件之前检查哪些路径。 – 2010-08-06 07:42:55

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;