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