技术开发 频道

PHP开发经典教程 (Part7):面向对象编程

父类与子类 

    无论是在PHP 4还是在PHP 5中,OOP两个最好的特点就是可扩展性和继承。非常简单,这意味着你可以在现有的类的基础上创建一新类,给它增加新的特征(读取:属性和方法),然后在该新类的基础上创建对象。这些对象将会包含原始父类的所有特征,以及子类的新特征。 

    作为解释说明,考虑下面的PolarBear()类,该PolarBear()类用新方法扩展了Bear()类。

<?php // PHP 5 // class definition class Bear { // define properties public $name; public $weight; public $age; public $sex; public $colour; // constructor public function __construct() { $this->age = 0; $this->weight = 100; } // define methods public function eat($units) { echo $this->name." is eating ".$units." units of food... "; $this->weight += $units; } public function run() { echo $this->name." is running... "; } public function kill() { echo $this->name." is killing prey... "; } public function sleep() { echo $this->name." is sleeping... "; } } // extended class definition class PolarBear extends Bear { // constructor public function __construct() { parent::__construct(); $this->colour = "white"; $this->weight = 600; } // define methods public function swim() { echo $this->name." is swimming... "; } } ?>


    扩展关键字用于将父类扩展为子类。父类所有的函数和变量对于子类而言立即变得可用。这一点在下列代码段中清晰可见:

<?php // create instance of Bear() $tom = new Bear; $tom->name = "Tommy Bear"; // create instance of PolarBear() $bob = new PolarBear; $bob->name = "Bobby Bear"; // $bob can use all the methods of Bear() and PolarBear() $bob->run(); $bob->kill(); $bob->swim(); // $tom can use all the methods of Bear() but not PolarBear() $tom->run(); $tom->kill(); $tom->swim(); ?>

 

    在该实例中,对$tom->swim()的最后调用将失败从而引起一个错误,因为Bear()类没有包含swim()方法。然而,对$bob->run()或$bob->kill()的调用没有一个失败的,这是因为作为Bear()类的子类,PolarBear()继承了其父类的所有方法和属性。 

    请注意,父类构造器是如何在PolarBear()子类构造器中被调用的,这样做是一个好主意,其目的在于当子类实例化时父类的所有必须的初始化得到了执行。然后子类特定的初始化可以在子类构造器中完成。只在子类没有构造器时,父类的构造器才会被自动调用。 

    你也可以在PHP 4中这样做。下面是PolarBear类定义的PHP 4 版本。

<?php // PHP 4 // extended class definition class PolarBear extends Bear { // constructor function PolarBear() { parent::Bear(); $this->colour = "white"; $this->weight = 600; } // define methods function swim() { echo $this->name." is swimming... "; } } ?>

    为了防止类或其方法被继承,请在类或者方法的名字前使用关键字final(这是PHP 5中的新特征,无法在PHP的先前版本中实现)。下面是一个使得Bear()类不可继承(如果那确实是一个单词的话)的例子:

<?php // PHP 5 // class definition final class Bear { // define properties // define methods } // extended class definition // this will fail because Bear() cannot be extended class PolarBear extends Bear { // define methods } // create instance of PolarBear() // this will fail because Bear() could not be extended $bob = new PolarBear; $bob->name = "Bobby Bear"; echo $bob->weight; ?>

 

 

0
相关文章