Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^4) CHAPTER 1 ■ ABSTRACT CLASSES, INTERFACES, AND PROGRAMMING BY CONTRACT
Because an abstract class does not define the implementation for every method it declares, it
cannot be instantiated directly with the new operator. Instead, a separate class must be created
that extends the abstract class and overrides any previously declared abstract prototypes. In
extending the class, you will be able to create specialized objects that still maintain a common
set of functionality.
To get the most out of abstract classes, you should remember the following rules:



  • Any class that contains even one abstract method must also be declared abstract.

  • Any method that is declared abstract, when implemented, must contain the same or
    weaker access level. For example, if a method is protected in the abstract class, it must
    be protected or public in the inheriting class; it may not be private.

  • You cannot create an instance of an abstract class using the new keyword.

  • Any method declared as abstract must not contain a function body.

  • You may extend an abstract class without implementing all of the abstract methods if
    you also declare your extended class abstract. This can be useful for creating hierarchical
    objects.


To declare a class as abstract you use the abstract modifier in the class declaration. The
code presented in Listing 1-1 defines one abstract class with both a fully declared method and
an abstract method that will be implemented later.

Listing 1-1. Defining a Basic Abstract Class

abstract class Car {

//Any base class methods

abstract function getMaximumSpeed();

}

This class by itself is not particularly useful because it is abstract and cannot be instanti-
ated. To make this class useful and obtain an instance, you must first extend it. For example,
you can create a class named FastCar that inherits from Car and defines a getMaximumSpeed()
method, as shown in Listing 1-2.

Listing 1-2. Inheriting an Abstract Class

class FastCar extends Car {

function getMaximumSpeed() {
return 150;
}

}

McArthur_819-9C01.fm Page 4 Tuesday, December 18, 2007 7:38 AM

Free download pdf