Object-Oriented PHP - Concepts, Techniques, And Code

Page 113

OOPHP_02.book Page 93 Friday, May 5, 2006 2:25 PM

flexibility of interfaces. PHP doesn’t allow multiple inheritance for classes; a child class may have only one parent class. However, you can implement any number of interfaces. It makes more sense to use abstract classes when there is a mix of concrete and abstract methods. You can provide an implementation where identical, derived class behavior is expected, and you can provide an abstract method where behavior will differ. You could, of course, ignore methods for which you expect the behavior of derived classes to diverge, but by declaring a method abstract you ensure that it will be implemented in any derived class. You’ll see how this can be used to your advantage in the following discussion of polymorphism.

Polymorphism In Chapter 10 you created a MySQLException class by inheriting from Exception. Type hinting allowed you to easily distinguish different kinds of exceptions and made it possible to have more than one catch block. However, when using type hinting, you also had to order the catch blocks carefully to make sure that the child preceded the parent. Specifically, MySQLException had to precede Exception because a catch block that catches the Exception class will also catch any derived class. Because it is derived from Exception, MySQLException can be caught by an Exception catch block. A parent class can stand in for its children, but a child cannot stand in for its parent. (This may look like a drawback, but you’ll soon see how it can be used to advantage.)

Controlling How Functions Are Used Type hinting can give a programmer more control over the way that a function is used. Suppose you derive a Canary class and a Lark class from the Bird class shown in Listing 11-1. You could pass either a canary or a lark to the function in Listing 11-2. function doSomething(Bird $b){ //do something $b->sing(); //do something else } Listing 11-2: A function that uses type hinting to specify a Bird object

Even though the Bird class is an abstract class that cannot be instantiated, you can use it to type hint the argument to this function in exactly the same way that catch blocks are type hinted. In Listing 11-2, type hinting prohibits passing anything but a bird to the function—passing any other object or a primitive will result in an error. In this way, a programmer can restrict the way that a function is used. With properly ordered catch blocks you used type hinting to catch specific kinds of exceptions. The doSomething function does the converse; it catches any kind of Bird. The ability to pass any kind of Bird to this function without knowing the Ad van ce d O b jec t -O rie nt ed Pr og ra mm in g C on cep t s

93


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.