PHP Abstract Class

In this chapter you will learn:

  1. What is an abstract class
  2. Syntax for abstract class
  3. Note for abstract class
  4. Example - abstract class

Description

Abstract class defines an abstract concept, for example number is an abstract concept while int, byte are concrete concepts. Vehicle is an abstract concept while car and ship are concrete concepts.

Abstract class is for inheriting to create a new, non-abstract (concrete) class.

By making a parent class abstract, you define the rules as to what methods its child classes must contain.

An abstract method in the parent class doesn't actually have any code in the method.

It leaves that up to the child classes. It specifies what the child class must do, not how to do it.

Syntax

To declare an abstract method, simply use the abstract keyword, as follows:

abstract public function myMethod( $param1, $param2 );

We can optionally specify any parameters that the method must contain.

However, you don't include any code that implements the method, nor do you specify what type of value the method must return.

If you declare one or more methods of a class to be abstract, you must also declare the whole class to be abstract, too:


abstract class MyClass { 
    abstract public function myMethod( $param1, $param2 ); 
}   

Note

You can't instantiate an abstract class-that is, create an object from it-directly:


// Generates an error: "Cannot instantiate abstract class MyClass" 
$myObj = new MyClass;   

Example 1


<?PHP/*from ja v a  2s  .c o  m*/
abstract class Book {
        private $Name;
        public function getName() {
            return $this->Name;
        }
}
?>

As mentioned already, you can also use the abstract keyword with methods, but if a class has at least one abstract method, the class itself must be declared abstract.

You will get errors if you try to provide any code inside an abstract method, which makes this illegal:


<?PHP//  j  av a 2 s .  co m
abstract class Book {
        abstract function say() {
                print "Book!";
        }
}
?>

This is illegal as well:


<?PHP/*  j a va2s  .  c  o m*/
abstract class Book {
        abstract function say() { }
}
?>

Instead, a proper abstract method should look like this:


<?PHP/*  ja  v  a2 s.co m*/
abstract class Book {
        abstract function say();
}
?>

Next chapter...

What you will learn in the next chapter:

  1. What are PHP Class Access Control Modifiers
  2. List of Access Control Modifiers
  3. Public
  4. Private
  5. Protected
Home » PHP Tutorial » PHP Class Definition
Concept for Object Oriented Design
PHP Class Definition
PHP Create Object from Class
PHP Class Properties
PHP Iterating Object Properties
PHP Class Inheritance
PHP Overriding Methods
PHP final Classes and Methods
PHP Abstract Class
PHP Class Access Control Modifiers
PHP Class Constructor
PHP Class Destructors
PHP Class Magic Methods