【问题标题】:Create instance of subclass within static method in abstract superclass? [duplicate]在抽象超类的静态方法中创建子类的实例? [复制]
【发布时间】:2019-04-15 12:06:14
【问题描述】:

如何在 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”

有道理!但是我想要创建一个实现子类的实例。这可能吗?在某些情况下是否有意义?

【问题讨论】:

    标签: php inheritance static abstract-class subclass


    【解决方案1】:

    没关系,我找到了方法:

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

    【讨论】:

    • 很高兴看到您想出了办法。另一种方法是使用new static() 而不是new self()
    • 谢谢,这样更好!
    猜你喜欢
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-14
    • 2013-08-02
    • 2021-05-14
    • 1970-01-01
    相关资源
    最近更新 更多