0

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?

j08691
  • 204,283
  • 31
  • 260
  • 272
Blackbam
  • 17,496
  • 26
  • 97
  • 150

1 Answers1

0

Nevermind I have found a way:

abstract class GenericUserMessage {

    protected abstract function instantiate($key,$message,string $type = NoticeTypes::INFO);

    public static function createOrUpdate($key,$message,string $type = NoticeTypes::INFO) {
        if(self::exists($key)) {
            self::updateMessage($key,$message,$type);
        } else {
            self::instantiate($key,$message,$type);
        }
    }

}
Blackbam
  • 17,496
  • 26
  • 97
  • 150