为了账号安全,请及时绑定邮箱和手机立即绑定

PHP 父类调用子类的重写方法

PHP 父类调用子类的重写方法

PHP
慕码人2483693 2019-03-12 10:06:11
有没有大神 写个demo 帮我 解释下这个问题 这是baseModel 这是teacherModel 继承 baseModel, 里面写了一个formatList 我在controller中调用 并没有用到teacherModel 的 formatList 没有打印的数据
查看完整描述

2 回答

?
慕无忌1623718

TA贡献1744条经验 获得超4个赞

$this->format();

直接调用就行了啊,显然你没有理解继承中的重写

class ModelB
{
    public function getList()
    {
        echo 'ModelB:getList';
        $this->format();
    }
    public function format()
    {
        echo 'ModelB:format';
    }
}
class ModelA extends ModelB
{
    public function format()
    {
        echo 'ModelA:format';
    }
}
(new ModelA)->getList();//ModelB:getList-ModelA:format-
查看完整回答
反对 回复 2019-03-18
?
呼如林

TA贡献1798条经验 获得超3个赞

<?php
class ModelB
{
    public function getList()
    {
        $this->format();
    }
    public function format()
    {
        echo "I am ModelB".PHP_EOL;
    }

}

class ModelA extends ModelB
{
    public function format()
    {
        echo "I am ModelA".PHP_EOL;
    }

}

class ControllerC
{
    public $obj;
    public function __construct()
    {
        $this->obj = new ModelA();
    }

    public function handle()
    {
        $this->obj->getList();
    }

}

$obj = new ControllerC();
$obj->handle(); //输出"I am ModelA"
查看完整回答
反对 回复 2019-03-18
  • 2 回答
  • 0 关注
  • 812 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信