The blueprints of dog breeds and animals are known as classes - they define the basic architecture of the objects available in our programs. Each class is defined as having a set of functions and variables, and you can inherit one class from another - our Breed classes, for example, inherited from the Dog class, thereby getting all the Dog functions and variables available. Inheriting is often referred to a sub-classing - "poodle" would be a sub-class of "dog".

Some languages, such as C++, allow you to inherit from more than one class, which is known as multiple inheritance. This technique allows you to have a class bird and a class horse, then create a new class called "Flying Horse", which inherits from both bird and horse, to give you animals like the mythical Pegasus. PHP does not allow you to do this because it generally makes for very confusing programs, and is quite rare even in C++.

PHP allows you to inherit from precisely one parent class, and you can inherit as many times as you want. For example, the dog class could inherit from the class Carnivora, which would contain cats, dogs, bears, etc. Carnivora could inherit from Mammalia, which holds all mammals, which could in turn inherit from Vertebrata, holding all animals with a backbone, etc - the higher up you go, the more vague the classes become. This is because each class inherits the functions and variables from its parent class, as well as adding its own.

Author's Note: people often use the terms "parent", "child", "grandparent", etc, to define their class structure. A child class is one that inherits from another - "poodle" is a child of "dog", and would be a grandchild of "carnivora". "Carnivora" would be the parent of "dog" and grandparent of "poodle" - this will make more sense later, when you are creating your own classes and sub-classing freely.


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Defining a class >>

Previous chapter: Conceptual overview

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.