2010-05-20 172 views
4
abstract class db_table { 

    static function get_all_rows() { 
     ... 
     while(...) { 
      $rows[] = new self(); 
      ... 
     } 
     return $rows; 
    } 
} 

class user extends db_table { 

} 

$rows = user::get_all_rows(); 

我想從抽象父類中定義的靜態方法創建一個類的實例,但PHP告訴我:「致命錯誤的靜態函數創建一個新的實例:不能實例化抽象類.. 。「我應該如何正確實施?在抽象類

編輯:當然,我想在這種情況下創建類「用戶」的實例,而不是抽象類。所以我必須告訴它創建一個被調用的子類的實例。

回答

9

this page手冊中:

Limitations of self::

Static references to the current class like self:: or __CLASS__ are resolved using the class in which the function belongs, as in where it was defined.

只有解決這個使用PHP> = 5.3和後期靜態綁定表的簡單方法。在PHP 5.3這應該工作:

static function get_all_rows() { 
     $class = get_called_class(); 
     while(...) { 
      $rows[] = new $class(); 
      ... 
     } 
     return $rows; 
    } 

http://php.net/manual/en/function.get-called-class.php

+0

謝謝!工作很好。 – arno 2010-05-20 12:42:51

+0

提示:可以使用以下代碼在PHP <5.3中模擬get_called_class:http://www.php.net/manual/en/function.get-called-class.php#93799 – arno 2010-05-20 12:46:59

1

這項工作對我來說..

abstract class db_table { 

static function get_all_rows() { 
    ... 
     while(...) { 
      $rows[] = new static(); 
      ... 
     } 
     return $rows; 
    } 
}