Create a new instance in a static function of an abstract class

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 instantiate a class from a static method defined in an abstract parent class, but PHP tells me: "Fatal error: cannot instantiate an abstract class ..." How to implement it correctly?

Edit: Of course, I want to create instances of the user class in this case, not an abstract class. So I have to tell him to instantiate the called subclass.

+4
source share
2 answers

See this page in the manual:

self:: limitations self::

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

There is only an easy way to use PHP> = 5.3 and late static bindings. In PHP 5.3, this should work:

 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

+10
source

this work is for me ..

 abstract class db_table { static function get_all_rows() { ... while(...) { $rows[] = new static(); ... } return $rows; } } 
+2
source

Source: https://habr.com/ru/post/1310367/


All Articles