douhuocuo9012 2017-01-28 14:49
浏览 99
已采纳

PHP抽象类和受保护的方法

Like title say I have a problem with this code:

abstract class AClass {
    abstract protected function a1();
    abstract protected function a2();

    public function show() {
        return $this->a1() . "<br>" . $this->a2();
    }
}


class A1 extends AClass {

    protected function a1() {
        return 'A1a1';
    }

    protected function a2() {
        return 'A1a2';
    }
}

class A2 extends AClass {

    protected function a1() {
        return 'A2a1';
    }

    protected function a2() {
        return 'A2a2';
    }
}

class AA {

    public function __construct() {
        $a11 = new A1();

        $a22 = new A2();

        $this->inter($a11);
        $this->inter($a22);
    }

    private function inter(AClass $class)  {
        echo $class->show();
    }
}

$aa = new AA();

It is throwing:

Fatal error: Call to protected A1::a1() from context 'AA' in C:\xampp\htdocs\Learning\index.php on line 38

Line 38 is this:

$a11 = new A1();

I do not understand why it is throwing that error if I'm not calling a1() at that line.

Thanks and regards

Javier

  • 写回答

1条回答 默认 最新

  • dongluobei9359 2017-01-28 16:56
    关注

    At line 38 you make an instance of class A1, so the constructor is called: it is the function a1() on line 15. Since class names are case-insensitive, so are constructor names, too.

    Since your constructor is protected, it cannot be called from outside of the class. Maybe you can make a public static function, call that without instantiation, and inside of it you can call the constructor. It can be good for the Singleton class design pattern.

    If you want to test only the abstraction with normal methods, simply rename your functions, so they will not be constructors.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在