加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 如何访问子方法

发布时间:2020-12-13 21:54:05 所属栏目: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 me
你如何访问子方法,例如?

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

解决方法

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

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

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

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

你在这里尝试做的事听起来非常像抽象类的用例:

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

    abstract function Run();
}

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

抽象声明将通过尝试实例化和启动A而不扩展和定义所需方法来精确地防止您自己射击.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读