9.3 Inheritance


You need to create a new class that is derived from an existing class.

Technique

Java programmers will be familiar with the extends keyword, which enables you to declare a new class that inherits methods and variables from a parent class. PHP's syntax is the same:

 <?php class Car extends Vehicle {     var $body_type;     var $engine;     function initialize($body_type, $engine) {         $this->body_type = $body_type;         $this->engine = $engine;     } } ?> 

Comments

The extends statement tells PHP to make a new class and automatically inherit the parent class's variables and methods. The extended or derived class can have all the variables and methods of the base class, and you can add or override variables and methods in its definition (known as overriding):

 <?php class Pet {     var $food = array();     var $water;     function eat() {         foreach ($this->food as $snack) {             print $snack;         }     } } class Dog extends Pet {      function set_food() {         $this->food = array('Iams', 'Meat', 'Alpo');      } } $obj = &new Dog; $obj->set_food(); $obj->eat(); ?> 

Notice that there is no eat() method in the Dog class because the Dog class extends the Pet class, and so it inherits the methods from the Pet class. Therefore, the eat() method is inherited from the Pet class.

Note that when you inherit constructors, the parent class's constructor is not called if the inherited class is a constructor. For more information, see recipe 9.5.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net