2010-08-06 50 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;