Monday, December 1, 2014

Learn Abstract Class Tutorial in PHP

Here, You will find the detail about the abstract class that why it is necessary in codes and how to show it.

Abstract Class Tutorial in PHP

Tutorial on Abstract Class :-

Abstract class defines the blueprint for child classes that inherits them.

Some Important Points About Abstract Class :-

1. Methods in abstract class can not be private.

2. Abstract class can not be used directly.

3. Abstract class can contain non-abstract methods also.

When we can use Abstract Class ?? :-

There are many situations, in which we need to use it. First of all, to organize the code it is better to make them abstract class. All child classes which share common functionality, must extend the parent class. So, You can reduce the code duplication. Additionally, you can easily change the figure in code.

Let’s create one abstract class car. Every car has their own model type such as BMW, Swift, HondaCity, which they need to define. Each car shares some common functionality, let’s say all cars have four wheels.

abstract class car{

   /* Abstract method, this must be define in child class. */

    abstract public function modelType();

   /* Concrete method, which is same in all classes. */

    public function wheelCount() {

      echo "I have four wheels";
    }

}
We can not create an object of abstract class directly. Here, Check what happens if i try to create an object.

$data = new car;

Then it gives following error.

PHP Fatal error: Cannot instantiate abstract class. So remember you can’t instantiate abstract classes.

Create child class, which inherits abstract class.

class HondaCity extends car{

    public function modelType(){

        echo "HondaCity";
    }
}

$data = new HondaCity;

$data->modelType();

/* Common method, i can access using child class object. */
$data->wheelCount();
class Swift extends car {

public function modelType() {
echo "swift";
}
}

$data = new Swift;

$data->modelType();

$data->wheelCount();

Organize your code in a better way by using Abstract Class. 

0 comments:

Post a Comment