Inheritance

To create a class that inherits functionality from a parent class, we need to alter our class declaration slightly. Listing 9.6 simplifies the Item class and creates an inheriting class called PriceItem.

Listing 9.6. Creating a Class That Inherits from Another
 1:<?php
 2:class Item {
 3:  var $name;
 4:
 5:  function Item( $name="item", $code=0) {
 6:    $this->name = $name;
 7:    $this->code = $code;
 8:  }
 9:
10:  function getName() {
11:   return $this->name;
12:  }
13: }
14:
15: class PriceItem extends Item {
16:
17: }
18:
19: $item = new PriceItem( "widget", 5442 );
20: print $item->getName ();
21: // outputs "widget"
22:
23: ?>

In addition to the simple Item class defined on line 2, we have created an even more basic PriceItem class on line ...

Get Sams Teach Yourself PHP in 24 Hours, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.