简体   繁体   English

从父级调用子级函数

[英]Call child function from parent

What is the best of calling a method in child class. 最好在子类中调用方法。 My IDE always shows Errors if i try to call the method directly. 如果我尝试直接调用该方法,则我的IDE始终显示错误。

    class Base
    {
        public function DoIt()
        {
            $this->Generate(); //How to check if child implements Generate?
        }
    }

    class Child extends Base
    {
       protected function Generate()
       {
            echo "Hi";
       }
    }

Simply put, you don't do this. 简而言之,您无需执行此操作。 It is very bad design: base classes should never assume anything about their descendants other than that they implement the contracts the base itself defines. 这是一个非常糟糕的设计:基类除了实现基本定义的协定之外,不应该假设任何有关其后代的东西。

The closest acceptable alternative would be to declare abstract protected function Generate() on the parent so that it knows that all derived classes implement it. 最接近的可接受替代方法是在父级上声明abstract protected function Generate() ,以便它知道所有派生类都将其实现。 Of course this is not meant to be a mechanical solution: you should only do it if Generate is meaningful for all descendants of Base . 当然,这并不意味着是机械的解决方案:只有在GenerateBase 所有后代有意义时,才应该这样做。

The issue is that your parent class doesn't define a Generate() method that a child class can override; 问题是您的父类没有定义子类可以覆盖的Generate()方法; you have to explicitly define this by creating an abstract method: 您必须通过创建抽象方法来明确定义此方法:

// class with at least one abstract method is 
abstract class Base
{
    public function DoIt()
    {
        $this->Generate();
    }

    // child classes MUST implement this method
    abstract protected function Generate();
}

You can loosen the requirements by creating an empty implementation in the parent class: 您可以通过在父类中创建一个空实现来放宽要求:

class Base
{
    public function DoIt()
    {
        $this->Generate();
    }

    // child classes MAY implement this method
    protected function Generate() {}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM