/*注:
两种方法即指:
1. abstract class aaa{} (注意aaa中只有抽象方法,没有一般方法)
class bbb extends aaa{} (在bbb中覆写aaa中的抽象方法)
2. interface aaa{}
class bbb implements aaa{} (在bbb中覆写aaa中的抽象方法)
*/
listing 6.13 abstract classes
//abstract root class 抽象根类
abstract class shape
{
abstract function getarea(); //定义一个抽象方法
}
//abstract child class 抽象子类
abstract class polygon extends shape //多边形
{
abstract function getnumberofsides();
}
//concrete class 实体类 三角形类
class triangle extends polygon
{
public $base;
public $height;
public function getarea() //覆写计算面积方法
{
return(($this->base * $this->height)/2);
}
public function getnumberofsides() //覆写边数统计方法
{
return(3);
}
}
//concrete class 实体类四边形
class rectangle extends polygon
{
public $width;
public $height;
public function getarea()
{
return($this->width * $this->height);
}
public function getnumberofsides()
{
return(4);
}
}
//concrete class 实体类 圆形
class circle extends shape
{
public $radius;
public function getarea()
{
return(pi() * $this->radius * $this->radius);
}
}
//concrete root class 定义一个颜色类
class color
{
public $name;
}
$mycollection = array(); //建立形状的集合,放入数组
//make a rectangle
$r = new rectangle;
$r->width = 5;
$r->height = 7;
$mycollection[] = $r;
unset($r);
//make a triangle
$t = new triangle;
$t->base = 4;
$t->height = 5;
$mycollection[] = $t;
unset($t);
//make a circle
$c = new circle;
$c->radius = 3;
$mycollection[] = $c;
unset($c);
//make a color
$c = new color;
$c->name = "blue";
$mycollection[] = $c;
unset($c);
foreach($mycollection as $s)
{
if($s instanceof shape) //如果$s是shape类的实例
{
print("area: " . $s->getarea() . "n");
}
if($s instanceof polygon)
{
print("sides: " .$s->getnumberofsides()."n");
}
if($s instanceof color)
{
print("color: $s->name n");
}
print("n");
}
?>
新闻热点
疑难解答