Classes
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 methods and properties, and you can inherit one class from another—our Breed
classes, for example, inherited from the Dog
class, thereby getting all the Dog
methods and properties available. Inheriting is often referred to as subclassing—Poodle
would be a subclass 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 FlyingHorse
—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 Cat
, Dog
, Bear
, etc. Carnivora
could inherit from Mammalia
, holding 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 methods and properties from its parent class, as well as adding its own.
Tip
People often use the terms parent, child, grandparent, etc., to define their ...
Get PHP in a Nutshell 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.