How can I create an instance of a subclass within a static method within an abstract superclass in PHP?
My code is like this:
abstract class GenericUserMessage {
private $_message;
private $_type;
protected abstract function getAllMessages();
function __construct( $key, $message, string $type = NoticeTypes::INFO, $strict = false ) { // ... }
/**
* @param $key
* @param $message
* @param string $type
*/
public static function createOrUpdate($key,$message,string $type = NoticeTypes::INFO) {
if(self::exists($key)) {
self::updateMessage($key,$message,$type);
} else {
new self($key,$message,$type); // here is the error
}
}
}
class UserMessage extends GenericUserMessage {
protected function getAllMessages() {
// ...
return $all_messages;
}
}
This fails with the following fatal error:
Cannot instantiate abstract class 'GenericUserMessage'
Makes sense! However I want an instance of the implementing subclass to be created. Is this possible and can it make sense for certain situations?