PHP 5: Subclasses

Subclassing allows flexibility in code. E.g. there may be many types of User to a site. We can define subclasses of User such as AdminUser, RegisteredUser, UnregisteredUser which may share some common methods and properties but may have unique abilities. The syntax for this is simple:

class User
{
 //constructor function for User
 function User()
 {
 }
}
class AdminUser extends User
{
 //constructor function for AdminUser
 function AdminUser()
 {
 }
}

The method of logging in for all users may be the same, so we add a method to the User class:

class User
{
 //constructor function for User
 function User()
 {
 }

 function doLogin($username,$password)
 {
  //Code in here
  return $result;
 }
} 

As AdminUser extends User the method doLogin() will be defined (identically) for both classes.

Alternatively, a new method called doLogin() could be written specifically for AdminUser to handle a distinct situation. This can be tackled on a subclass-by-subclass basis e.g. AdminUser and RegisteredUser may use the common doLogin() method but UnregisteredUser has its own version.

N.B. The signatures of methods in subclasses must match that of the parent class (as PHP does not support overloading). Therefore a definition of

Public function doLogin($someArray)

In AdminUser would be invalid code (as it only accepts a single variable) and caught at compilation time (i.e. before runtime).

Next section: The constructor method

Advertisements
This entry was posted in PHP, Programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s