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

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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题