简体   繁体   English

PHP 抽象类和受保护的方法

[英]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致命错误:从第 38 行 C:\\xampp\\htdocs\\Learning\\index.php 中的上下文 'AA' 调用受保护的 A1::a1()

Line 38 is this:第 38 行是这样的:

$a11 = new A1();

I do not understand why it is throwing that error if I'm not calling a1() at that line.如果我不在该行调用 a1(),我不明白为什么它会抛出该错误。

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.在第 38 行,您创建了类 A1 的实例,因此调用构造function a1() :它是第 15 行的function a1() 。由于类名不区分大小写,因此构造函数名称也不区分大小写。

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.它对 Singleton 类设计模式很有用。

If you want to test only the abstraction with normal methods, simply rename your functions, so they will not be constructors.如果您只想使用普通方法测试抽象,只需重命名您的函数,这样它们就不会是构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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