4.5. Using Abstract Methods in Abstract Classes and Interfaces

You can use abstract methods that specify the information to be passed, but do not contain any code. Abstract methods were added in PHP 5. You can use abstract methods in abstract classes or in interfaces. An abstract class contains both abstract methods and nonabstract methods. An interface contains only abstract methods.

4.5.1. Using an abstract class

Any class that has an abstract method must be declared an abstract class. The function of an abstract class is to serve as a parent for a child class. You cannot create an object from an abstract class.

An abstract class specifies the methods for a child class. The child class must implement the abstract methods that are defined in the parent class, although each child class can implement the abstract method differently, with different code. If an abstract method specified in the parent class is not included in a child class, a fatal error occurs.

An abstract method specifies the values to pass, called the signature. The child implementation of the abstract method must use the same signature. The child must define the method with the same or weaker visibility. For example, if the abstract method is declared protected, the child implementation of the method must be declared protected or public.

The following code shows the use of an abstract class. An abstract class named Message is defined. Then two child classes are defined.

abstract class Message { protected message_content; ...

Get PHP & MySQL® Web Development All-in-One Desk Reference for Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.