duanchun1881 2018-11-12 18:07
浏览 86

PHP:在抽象超类中的静态方法中创建子类的实例? [重复]

This question already has an answer here:

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?

</div>
  • 写回答

1条回答 默认 最新

  • dongwh1992 2018-11-12 18:14
    关注

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

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿