你如何访问子方法

Jim*_*988 3 php

你如何访问子方法,例如?

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
Run Code Online (Sandbox Code Playgroud)

dec*_*eze 7

A不应该尝试调用它自己没有定义的任何方法.这适用于您的场景:

class A {
    public function Start() {
        $this->Run();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您实际执行此操作,它将会非常失败:

$a = new A;
$a->Start();
Run Code Online (Sandbox Code Playgroud)

你在这里尝试做的事听起来非常像一个abstract类的用例:

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

    abstract function Run();
}

class B extends A {
    public function Run() {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

abstract声明将通过尝试实例化Start A而不扩展和定义所需方法来精确地阻止您自己拍脚.