让我们想象一下,我们有以下接口声明.
<?PHP namespace App\Sample; interface A { public function doSomething(); }
和B类实现接口A.
<?PHP namespace App\Sample; class B implements A { public function doSomething() { //do something } public function doBOnlyThing() { //do thing that specific to B } }
C类将取决于接口A.
<?PHP namespace App\Sample; class C { private $a; public function __construct(A $a) { $this->a = $a; } public function doManyThing() { //this call is OK $this->a->doSomething(); //if $this->a is instance of B,//PHP does allow following call //how to prevent this? $this->a->doBOnlyThing(); } } ... (new C(new B()))->doManyThing();
如果实例类B被传递给C,那么PHP确实允许调用B的任何公共方法,即使我们只输入构造函数来接受A接口.
如何在PHP的帮助下防止这种情况,而不是依赖任何团队成员来遵守接口规范?
更新:让我们假设我不能将doBOnlyThing()方法设为私有,因为它在其他地方是必需的,或者它是我无法更改的第三方库的一部分.