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

Leave a Reply

Your email address will not be published. Required fields are marked *