To make this system more powerful, we don't want all users to have the same status in our group. Some users need administrators, other moderators, and other ordinary users only. How can we think of this in our object? The answer is inherited-the ability of a class to inherit methods and attributes from another category. First, let's take a look at the inheritance code:
/* Kirupa has admin powers */
$kirupa = new Admin( array( 'name' => 'Kirupa' ) );
echo $kirupa->getName().'<br />';// Kirupa
echo $kirupa->getAdmin(); // Administrator
/* Regular does not have admin powers */
$regular = new User( array( 'name' => 'Regular' ) );
$regular->getAdmin(); // breaks our code
/* Normal User class */
class User {
private $name;
function __construct( $attribs ) {
$this->name= $attribs['name'];
}
function getName() {
return $this->name;
}
}
/* Admin is a User, but with additional functionality */
class Admin extends User {
function getAdmin() {
return 'Administrator';
}
}
As you can see, our Admin object inherits the functionality of the user-level using keyword extensions. Most importantly, our management is provided with some additional functionality. In this case, our user level is called hyper. In PHP, a class can only inherit one of the parents. There are more subtle inheritances, but this tutorial will only cover the basics. In a more realistic scenario, we will have more functional code only for administrators. Maybe it's like:
/* Additional functionality for just Administrators */
class Admin extends User {
function banUser( $id ) {
/* code to ban user */
}
function unbanUser( $id ) {
/* code to unban or activate user account */
}
//...
}
For time and focus, these methods do not really get coded. However, this should give you some insight into how to inherit the work, and why it can be useful.
Continued in a few parting words and directions.
Word segmentation
Until now, you should know about objects, how to create them, and how to get into their properties and methods. This tutorial is by no means exhaustive. In fact, this is just the tip of the iceberg, which is the purpose. For further reading, I suggest PHP5: object, pattern, and practice of Matt Zandstra. In addition, you can read the object provided by the file on Php.net.
As you begin to learn more about object-oriented and your PHP code becomes more object-oriented, you will find more code reuse and ultimately save time and energy. Pre-existing code resources, such as pears and phpclasses.org, will become increasingly useful.