在抽象类的静态函数中创建一个新实例
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 告诉我“致命错误:无法实例化抽象类...”我应该如何正确实现它?
编辑:当然,在这种情况下我想创建“user”类的实例,而不是抽象类的实例。所以我必须告诉它创建被调用子类的实例。
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();
I want to create instances of a class from a static method defined in the abstract parent class but PHP tells me "Fatal error: Cannot instantiate abstract class ..." How should I implement it correctly?
Edit: Of course I want to create instances of the class "user" in this case, not of the abstract class. So I've to tell it to create an instance of the called sub-class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请参阅手册中的此页面:
只有使用 PHP >= 5.3 和后期静态绑定来解决这个问题。在 PHP 5.3 中,这应该可以工作:
http://php.net/manual/ en/function.get-used-class.php
See this page in the manual:
There is only an easy way around this using PHP >= 5.3 and late static bindings. In PHP 5.3 this should work:
http://php.net/manual/en/function.get-called-class.php
这对我来说工作..
this work for me..