How to access child method

How can I access a child method for example?

class A
{
    public function Start()
    {
        // Somehow call Run method on the B class that is inheriting this class
    }
}

class B extends A
{
    public function Run()
    {
        ...
    }
}

$b = new B();
$b->Start(); // Which then should call Run method

      

+3


source to share


2 answers


A class A

should not attempt to call any methods that it does not define itself. This will be fine for your scenario:

class A {
    public function Start() {
        $this->Run();
    }
}

      

However, it will fail if you actually do this:

$a = new A;
$a->Start();

      



What you are trying to do here is very similar to the usage for classes abstract

:

abstract class A {
    public function Start() {
        $this->Run();
    }

    abstract function Run();
}

class B extends A {
    public function Run() {
        ...
    }
}

      

The declaration abstract

will definitely prevent you from shooting your own leg trying to instantiate and Start

A

without extending and defining the required methods.

+7


source


If B inherits from A, then B will look like this:

      class B extends A
{
    public function Start()
    {
        ...
    }
    public function Run()
    {
        ...
    }
}

      



Since Run () and Start () are in the same class, we can directly call Run () in Start ().

public function Start()
{
    Run();
}

      

0


source







All Articles