Page 242 - Beginning PHP 5.3
P. 242
Part II: Learning the Language
public function getArea() {
return $this- > _width * $this- > _height;
}
}
Now the ShapeInfo::showInfo() method works correctly with Rectangle objects:
$myRect = new Rectangle;
$myRect- > setColor( “yellow” );
$myRect- > fill();
$myRect- > setWidth( 4 );
$myRect- > setHeight( 5 );
$info = new ShapeInfo();
$info- > setShape( $myRect );
$info- > showInfo(); // Displays “The shape’s color is yellow, and its area
is 20.”
Working with Interfaces
In the previous section you learned how you can use abstract classes to force all child classes of a given
class to implement a consistent set of methods. Interfaces work in a similar way, in that they declare
a consistent set of methods that classes must implement. However, whereas an abstract class has a
parent - child relationship with the class that extends it, this relationship doesn ’ t exist with interfaces.
Instead, a class implements an interface. (At the same time, the class can also extend a parent class.)
Because interfaces lie outside the inheritance hierarchy, you can create classes of totally different ancestry
that can still implement the same interface. To give a practical example, a television is a very different
kind of object to a tennis ball, and each type of object will have very different properties and behaviors.
Yet an online retailer might well sell both televisions and tennis balls. By creating a Sellable interface,
and making both Television and TennisBall classes implement that interface, you can ensure that
both classes contain methods such as sellItem() , deliverItem() , and getStockLevel() , allowing
Television and TennisBall objects to be sold in the online store.
What ’ s more, a class can implement more than one interface at once (provided the method names
declared in the interfaces don ’ t clash), which allows you to build very powerful, adaptable classes that
can be used in lots of situations.
You create an interface much like a class, except that you use the keyword interface rather than
class . You then specify a list of methods that implementing classes must include:
interface MyInterface {
public function myMethod1( $param1, $param2 );
public function myMethod2( $param1, $param2 );
}
Interfaces can ’ t contain properties; they can only contain method declarations (which can ’ t contain any
implementation code). What ’ s more, all methods in an interface must be public (otherwise it wouldn ’ t be
much of an interface!).
204
9/21/09 9:03:44 AM
c08.indd 204
c08.indd 204 9/21/09 9:03:44 AM