samedi 28 janvier 2017

PHP abstract classes and protected methods

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

Aucun commentaire:

Enregistrer un commentaire