PHP:在抽象超类的静态方法中创建子类的实例吗?

时间:2018-11-12 18:07:02

标签: php inheritance static abstract-class subclass

如何在PHP的抽象超类中的静态方法中创建子类的实例?

我的代码是这样的:

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;
    }
}

此操作失败,并出现以下致命错误:

  

无法实例化抽象类'GenericUserMessage'

说得通!但是我想创建实现子类的实例。这可能吗?在某些情况下是否有意义?

1 个答案:

答案 0 :(得分:0)

没关系,我找到了一种方法:

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);
        }
    }

}