教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 php抽象类和抽象方法的例子

php抽象类和抽象方法的例子

发布时间:2017-01-21   编辑:jiaochengji.com
本文介绍下,php抽象类与抽象方法的一个例子,学习下php中抽象类与抽象方法的实现方法,有需要的朋友参考下。

在php中的任何类,它包含一个或多个抽象方法时,则必须声明为抽象类。
抽象类不能实例化。
一个类,如果它扩展了抽象类,则必须实现父类的抽象方法。

例子:
 

复制代码 代码示例:

<?
/**
* php抽象类与抽象方法的例子
* edit: www.jbxue.com
*/
abstract class Animal{
    function __construct($name='No-name', $breed='unknown', $price = 15) {
        $this->name = $name;
        $this->breed = $breed;
        $this->price = $price;
    }
    function setName($name) {
        $this->name = $name;
    }
    function setBreed($breed){
        $this->breed = $breed;
    }
    function setPrice($price) {
        $this->price = $price < 0 ? 0 : $price;
    }
    function getName() {
        return $this->name;
    }

    function display() {
        printf("<p>%s is a %s and costs \$%.2f.</p>\n", $this->name, $this->breed, $this->price);
    }
    public static $type = "animal";
   
    public static function fly($direction = 'around') {
        printf("<p>Flying %s.</p>\n", $direction);
    }
    abstract public function birdCall();   
}

class Parrot extends Animal {
    public function birdCall($singing=FALSE) {
        $sound = $singing ? "twitter" : "chirp";
        printf("<p>%s says: *%s*</p>\n", $this->getName(), $sound);
    }
}
?>

您可能感兴趣的文章:
php中关于抽象(abstract)类和抽象方法的问题解析
php中抽象方法与普通方法的主要区别是什么
php抽象类和接口的概念与区别
php 抽象方法和普通方法的区别
php入门教程(十八) php抽象类与接口
php 面向对象详解_对象的串行化和反串行化
php抽象类和抽象方法的例子
一文搞懂PHP类和对象、抽象类、接口
PHP抽象类和接口示例和区别
python抽象类有什么用

关键词: php抽象方法  php抽象类   
[关闭]
~ ~