ÄúµÄλÖãºÑ°ÃÎÍøÊ×Ò³£¾±à³ÌÀÖÔ°£¾PHP ±à³Ì£¾PHP 5 Power programming
Team LiB
Previous Section Next Section

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.


    Team LiB
    Previous Section Next Section