简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM