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

Posted

技术标签:

【中文标题】在抽象超类的静态方法中创建子类的实例? [复制]【英文标题】: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”

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

【问题讨论】:

【参考方案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() 谢谢,这样更好!

以上是关于在抽象超类的静态方法中创建子类的实例? [复制]的主要内容,如果未能解决你的问题,请参考以下文章