|
This is a nice part, inheritance provides the means for realizing abstraction layers. You can have a class Animal, a class Mammal and a class Cow for creating Dolly the cow. Each class should inherit from the previous one properties and methods while introducing new ones. The grand-parent class is the Animal class and the ultimate child class is the Cow one whereas Dolly is just an object of the latter. The property weight applies to all animals whereas the property number of legs should be introduced at the Mammal level, the method moo should only appear in the Cow class. Think of our User class, say you need a set of attributes to distinguish between the rights administrators have; some are just editors, others can also be publishers etc. If you want to incorporate every possible attribute into the User class you will end up with a very long list of member properties and a conceptually faulty model. The answer to this is introducing a class for creating administrators. But since we have a User class, it is not wise to replicate it into an Administrator class, best, the Administrator class should be a child of the User class inheriting all its properties and methods. We have to admit that inheritance assists semantically as well as having clear and readable code. Have a look at the following code. <? class User { var $name; var $username = "guest"; var $email; var $id = 1000; function __construct($newname, $lastid) { $this->name = $newname; $this->id = ++$lastid; } function setname($newname) { $this->name = $newname; } function getname() { return $this->name; } } ### Admin class is a child of the User class class Admin extends User { # additional properties for administrators var $editor = 1; var $publisher = 1; var $mobile; var $extension; # admin class constructor function __construct($newusername, $lastid, $newmobile, $newextension) { # User class member properties apply for the Admin class $this->username = $newusername; # optional call to the parent constructor parent::__construct("someone", $this->id); $this->mobile = $newmobile; $this->extension = $newextension; } function showuser() { print "\n NAME: $this->name [$this->username] ID:$this->id"; print "\n PRIV: $this->editor $this->publisher"; print "\n CONT: ext. $this->extension - mob. $this->mobile"; print "\n"; } } ### create a new user $harris = new Admin("sharris",0,"9600888888","4444"); $harris->setname("Steve Harris"); $harris->showuser(); ?> Just to mention here the epic term function overriding. If you have a parent and a child class having a method with the same name, the one more specific for an object is executed. We could have for example a showuser method in the User and the Admin classes, each printing different stuff then, we could call this method for an object without knowing its class. |