和集成抽象类需要使用 extends 关键字不同的是,实现接口使用的是 implements 关键字。一个类可以实现多个接口,这时,我们需要用逗号将他们隔开。如果将某个类标记为实现了某个接口,但却没有实现这个借口的所有方法,将会抛出错误。
2.2使用接口的案例
复制代码 代码如下:
<?php
abstract class Car
{
abstract function SetSpeend($speend = 0);
}
interface ISpeendInfo
{
function GetMaxSpeend();
}
class Roadster extends Car implements ISpeendInfo
{
public $Speend;
public function SetSpeend($speend = 0)
{
$this->Speend = $speend;
}
public function getMaxSpeend()
{
return $this->Speend;
}
}
class Street
{
public $Cars ;
public $SpeendLimit ;
function __construct( $speendLimit = 200)
{
$this -> SpeendLimit = $speendLimit;
$this -> Cars = array();
}
protected function IsStreetLegal($car)
{
if ($car->getMaxSpeend() < $this -> SpeendLimit)
{
return true;
}
else
{
return false;
}
}
public function AddCar($car)
{
if($this->IsStreetLegal($car))
{
echo 'The Car was allowed on the road.';
$this->Cars[] = $car;
}
else
{
echo 'The Car is too fast and was not allowed on the road.';
}
}
}
$Porsche911 = new Roadster();
$Porsche911->SetSpeend(340);
$FuWaiStreet = new Street(80);
$FuWaiStreet->AddCar($Porsche911);
/**
*
* @result
*
* The Car is too fast and was not allowed on the road.[Finished in 0.1s]
*
*/
?>
3.instanceof 操作符
instanceof 操作符是PHP5中的一个比较操作符。他接受左右两边的参数,并返回一个boolean值。这个操作符是用来确定对象的某个实例是否为特定的类型,或者是否从某个类型继承,又或者实现类某个特定的接口。
复制代码 代码如下:
echo $Porsche911 instanceof Car;
//result:1
echo $Porsche911 instanceof ISpeendInfo;
//result:1
4.契约式编程
契约式编程是指在编写类之前实现声明接口的一种编程实践。这种方法在保证类的封装性方面非常有用。使用契约式编程技术,我们可以在创建应用程序之前定义出视图实现的功能,这和建筑师在修建大楼之前先画好蓝图的做法非常相似。
5.总结
抽象类是使用 abstract 关键字声明的类。通过将某个类标记为抽象类,我们可以推迟实现所声明的方法。要将某个方法声明为抽象方法,只要去掉包含所有大括号的方法实体,将方法声明的代码行用分号结束即可。
抽象类不能直接实例化,他们必须被继承。
如果某个类从抽象类继承,当它没有实现基类中所声明的所有抽象方法时,它就必须也被声明为抽象的。
在接口中,我们可以声明没有方法体的方法原型,这点与抽象类很相似。他们之间的区别在于,接口不能声明任何具有方法体的方法;并且他们使用的语法也不一样。为了将揭开规则强制加到某个类上,我们需要使用implements关键字,而不是extends关键字。
有些情况下我们需要确定某个类是否是特定类的类型,或者是否实现了特定的接口。 instanceof 分成适合完成这个任务。instanceof 检查三件事情:实例是否是某个特定的类型,实例是否从某个特定的类型继承,实例或者他的任何祖先类是否实现类特定的接口。
某些语言具有从多个类继承的能力,这称为多重继承。PHP不支持多重继承。想法,他提供了为一个类声明多个接口的功能。
接口在声明类必须遵循的规则时非常有用。契约式编程技术使用这一功能来增强封装性,优化工作流。
您可能感兴趣的文章: