五环小胖子的博客

PHP面向对象学习笔记二

2013-07-11
Ryan
php

上篇文章我记录了一下关于PHP封装的知识,这篇文章我就记录一下关于PHP继承的知识吧。

三、PHP中的继承

1、extends关键字

PHP中的继承和严格意义上面向对象语言,比如:C#,是大同小异的。PHP中类的继承需要使用extends这个关键字

<?php
class Child extends father{
    ...
}
?>

看,是不是很简单,这样child类就继承了father类,子类中就把父类中不是用private修饰的属性和方法继承过来,当然,我们还可以在子类中定义新的方法和属性,这样做更有利于我们对代码的重用。举一个关于继承的小例子,如下:

<?php
class father{
    public $fproperty = 1;
    public function __construct(){}
    public function fmethod(){
        each $this->fproperty.'<br/>';
    }
}
class child extends father{
    public $cproperty = 2;
    public function __construct(){}
    public function cmethod{
        each $this->cproperty.'<br/>';
    }
}
$fobj = new father();
$cobj = new child();
$fobj->fmethod();
$cobj->cmethod();
$cobj->fmethod();
?>

以上代码输出的结果为:

1 2 1

2、final关键字

<?php
final class father{
    ...
}
?>

father就不能被其他的类继承了。

<?php
class father {
    ...
    final public function fmethod(){}
}
?>

类中fmethod就不能被子类继承了。

4、多继承

PHP只支持单重继承,而不支持多重继承,也就是说下面这样的代码是错误的

<?php
class father1{
    ...
}
class father2{
    ...
}
class child extends father1,father2{
    ....
}
?>

要想实现多重继承,我们可以用另一种方法,就是继承多接口。

<?php
interface Ifather1{
    ...
}
interface Ifather2{
    ...
}
class child implements Ifather1,Ifather2{
    ...
}
?>

我们看到在类继承接口时使用的是implements这个关键字,这个地方需要大家注意一下,不用和类继承类弄混了。


Similar Posts

Outline