简体   繁体   中英

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.

    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. 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 .

The issue is that your parent class doesn't define a Generate() method that a child class can override; 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() {}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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