PHP 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 w  ww  .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/*from   w w w  .j a v  a  2  s.c  om*/
abstract class Book {
        abstract function say() {
                print "Book!";
        }
}
?>

This is illegal as well:


<?PHP/*w ww . j  a v a2  s  . c  o  m*/
abstract class Book {
        abstract function say() { }
}
?>

Instead, a proper abstract method should look like this:


<?PHP//from w  w w  . j  a  va  2  s  . co m
abstract class Book {
        abstract function say();
}
?>




















Home »
  PHP Tutorial »
    Language Basic »




PHP Introduction
PHP Operators
PHP Statements
Variable
PHP Function Create
Exception
PHP Class Definition