Friday, July 18, 2014

Abstract class in PHP

Concept
Abstract class cannot be instantiated, that is we can not create a object. Any class which has at-least one abstract function should be  declared as abstract. These abstract functions are only can declare, can not define here. But these are must be defined in classes which are inherited this abstract class. We can declare this abstract function as any type(public, protected or private) in abstract class, but it should be same or less restricted type in inherited class(For example declared as protected may had public in derived class). And number of arguments also should be same(May had additional optional argument in derived class.).

Clear Example
<?php
abstract class A                          // Abstract class.
{
abstract protected function fun1();   // Declaring abstract function as protected.
abstract public function fun2($i);  // Declaring abstract function as public with one argument.
abstract public function fun3($i,$j); // Declaring abstract function as public with two arguments.

public function fun4()  // Declaring and defining a normal function in abstract class.
{
echo 'fun4 definition from class A(abstract class).<br />';
}
}

class B extends A
{
public function fun1()  // Definiion for a abstract function.
{
echo 'fun1 definition from class B.<br />';
}

public function fun2($i)  // Definiion for a abstract function with exact no.of arugument.
{
echo 'fun2 definition from class B.<br />';
}

public function fun3($i,$j,$k=30)  // Definiion for a abstract function with optional arugument.
{
echo 'fun3 definition from class B.<br />';
}
}

$b=new B();
echo $b->fun1();
echo $b->fun2(10);
echo $b->fun3(10,20);
echo $b->fun4();
?>

Abstract vs Interface
1. Abstract is a class but interface not. So memory allocation for abstract is high.
2. Abstract class can had normal functions and variables. But interface cannot.
3. Functions on interface must be public but in abstract class may had anything.
4. A class can inherit only one abstract class but can inherit more than one interface.

No comments:

Post a Comment

Learn JavaScript - String and its methods - 16

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>String and it's methods - JS&l...