Section 3.12. Abstract Methods and Classes


3.12. Abstract Methods and Classes

When designing class hierarchies, you might want to partially leave certain methods for inheriting classes to implement. For example, say you have the class hierarchy shown in Figure 3.2.

Figure 3.2. Class hierarchy.


It might make sense to implement setCenter($x, $y) in class Shape and leave the implementation of the draw() methods to the concrete classes Square and Circle. You would have to declare the draw() method as an abstract method so that PHP knows you are intentionally not implementing it in class Shape. The class Shape would then be called an abstract class, meaning that it's not a class with complete functionality and is only meant to be inherited from. You cannot instantiate an abstract class. You can define any number of methods as abstract, but once at least one method of a class is defined as abstract, the entire class needs to be declared as abstract, too. This double definition exists to give you the option to define a class abstract even if it doesn't have any abstract methods, and to force you to define a class with abstract methods as abstract so that it is clear to others what you had in mind.

The previous class diagram would translate into PHP code that's similar to the following:

 abstract class Shape {     function setCenter($x, $y) {         $this->x = $x;         $this->y = $y;     }     abstract function draw();     protected $x, $y; } class Square extends Shape {     function draw()     {         // Here goes the code which draws the Square         ...     } } class Circle extends Shape {     function draw()     {         // Here goes the code which draws the Circle         ...     } } 

You can see that the draw() abstract method does not contain any code.

Note

Unlike some other languages, you cannot define an abstract method with a default implementation. In PHP, a method is either abstract (without code) or it's fully defined.




    PHP 5 Power Programming
    PHP 5 Power Programming
    ISBN: 013147149X
    EAN: 2147483647
    Year: 2003
    Pages: 240

    Similar book on Amazon

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net