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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?