如果我在 PHP 中定义一个接口,以及一个创建该接口实例的工厂类,有什么方法可以强制客户端代码仅使用该接口而不使用底层具体类?根据我的理解,客户也可以实际使用底层类中的任何公共函数/字段。
这是一个例子:
<?php
interface IMyInterface
{
public function doSomething();
}
?>
<?php
class ConcreteImplOfMyInterface implements IMyInterface
{
const NotPartOfInterface = 'youcantseeme';
public function doSomething()
{
}
}
?>
<?php
class MyInterfaceFactory
{
public static function createMyInterface()
{
return new ConcreteImplOfMyInterface();
}
}
?>
<?php
function client()
{
$myInterface = MyInterfaceFactory::createMyInterface();
return $myInterface::NotPartOfInterface;
}
?>
这就是 PHP 中接口的优点的原因:
interface Printable{
public function display();
}
function display(Printable $obj){
$obj->display();
}
它要求进入该函数的任何变量都是 Printable 的实例。因此,如果您想使用该函数,则可以强制使用您的代码的任何人实现该接口。
PHP 5.1 http://php.net/manual/en/language.oop5.typehinting.php http://php.net/manual/en/language.oop5.typehinting.php
如果您想确保其他人无法使用类的特定方法或变量,您需要将这些方法和变量定义为private
。这将使它们无法被除该特定类之外的任何东西使用。 (甚至扩展您的类的类也不能使用它们)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)