2010-05-20 112 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; 
    } 
}