【问题标题】:How to use entityManagerInterface of parent class in child class?如何在子类中使用父类的entityManagerInterface?
【发布时间】:2023-01-18 05:42:20
【问题描述】:

我创建了一个抽象类,我计划在其中添加在子类中通用的函数。

class AbstractNews
{
    public function __construct(
        protected EntityManagerInterface $entityManager
    ) {
    }
}
class News extends AbstractNews
{
    public function __construct(
        protected EntityManagerInterface $entityManager,
    ) {
        parent::__construct($entityManager);
    }

我需要在子类和父类中定义EntityManagerInterface

有没有办法在父类中定义它并在子类中使用它?

【问题讨论】:

    标签: php symfony5


    【解决方案1】:

    是的,您可以在父类中定义 EntitiesManagerInterface 并通过将其作为父类构造函数的类型提示在子类中使用它。然后就可以在子类构造函数中调用父构造函数了。

    abstract class AbstractNews
    {
        protected EntitiesManagerInterface $entityManager;
    
        public function __construct(EntitiesManagerInterface $entityManager)
        {
            $this->entityManager = $entityManager;
        }
    }
    
    class News extends AbstractNews
    {
        public function __construct(EntitiesManagerInterface $entityManager)
        {
            parent::__construct($entityManager);
        }
    }
    

    你只需要在父类中定义一次EntitiesManagerInterface类型提示,它就会被子类继承。

    【讨论】:

      猜你喜欢
      • 2022-07-28
      • 1970-01-01
      • 1970-01-01
      • 2016-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      相关资源
      最近更新 更多