PHP 5: Abstract classes

Abstract classes are used to define operations and parameters but where you do not want a class instantiated directly. An abstract class must, therefore, have subclasses. In our example, we may not allow a type of general “User” but insist that a specific type is created. We can do this by defining the class as abstract:

abstract class User
{
 protected $logState;

 function User()
 {
  $this->logState = new LogState()
 }

 public function setLogin($loginValue)
 {
  $this->logState->setLogin(true);
 }

}

A call to $user = new User(); will now be invalid. Instead, we must call a subclass e.g. AdminUser.

An abstract class may contain abstract methods. These define the template for the method that must be implemented by each subclass. Abstract methods have no body, as with showNavigation() below:

abstract class User
{
 protected $logState;

 public function User()
 {
  $this->logState = new LogState()
 }

 public function setLogin($loginValue)
 {
  $this->logState->setLogin(true);
 }

 abstract public function showNavigation();
}

It would then be compulsory for each and every subclass of User to define a method called showNavigation() and to provide body code to perform the operation.

Next section: Static classes

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