by
Brian Haveri aka bwh2 | 31 December 2006In the
previous
page we covered a lot of territory, and we will wrap
things up on this page by covering the last topic,
Inheritance.
To make this system more robust, we don't want all of the
users in our group to have the same status. Some users need
to be administrators, others moderators, and others just
regular users. How can we account for this in our objects?
The answer is inheritance - the ability for one
class to inherit methods and properties from another class.
First, let's take a look at inheritance in code:
As you can see, our Admin
object has inherited the functionality of the
User
class using the keyword extends. On top of
that, our Admin is given some additional
functionality. In this case, our User class is
known as the superclass. In PHP, a class may only inherit
one superclass. There are more nuances to inheritance, but
this tutorial will only cover the basics. In a more
realistic scenario, we would code more functionality for
just administrators. Perhaps something like:
For the sake of time and focus, these methods haven't
actually been coded. But this should give you some insight
into how inheritance works and why it can be useful.
Continue on for a few parting words and direction.
By now, you should understand what objects, how to create
them, and how to access their properties and methods. This
tutorial is by no means all-encompassing. In fact, this is
just the tip of the iceberg and was designed as such. For
further reading, I suggest PHP5: Objects, Patterns, and
Practice by Matt Zandstra. In addition, you could read
through the
OOP documentation provided at php.net.
As you begin to understand OOP more and your PHP code
becomes more object oriented, you will find more code
reusable and ultimately save time and energy. Pre-existing
code resources such as
PEAR and
PHPClasses.org will become increasingly useful.
If you have questions related to this tutorial or PHP in
general, post them in the
Server-Side forum here at kirupa.com.
|