Tuesday, March 31, 2009

Abstract class and abstract method with example in php

In php, you can define a class as abstract class. In fact if you want to keep any method of a class as abstract that class must be declared as abstract class. So, there is both abstract classes and abstract methods.

A class defined as abstract class can't be instantiated, which means we can't create instance of that class but it can be subclassed. If methods are declared as abstract then they can't conatin implementation, that means without any braces and followed by semicolon(;) like,
abstract protected function display();

Abstract class may or may not include abstract methods.

When a subclass is inherited from abstract class all methods marked as abstract class declaration in the parent must be defined in the subclass.

The scope of the derived class method must be less restrictive than the scope of the base class method if it is declared as abstract method. For example, if base class abstract method is declared as protected then within derived class method or in other word the function implementation must be defined as either protected or public, but not private.

Below is an example of abstract class and abstract method in php,

<?php
abstract class AbstractClass{
//Only abstract class declartion here. Implementation must be inside subclass
abstract protected function abstractTest1();
abstract protected function abstractTest2($suffix);
public function display(){
echo $this->abstractTest1();
}
}

class SubClass1 extends AbstractClass{
protected function abstractTest1(){
return "SubClass1";
}
public function abstractTest2($suffix){
return "SubClass1 ".$suffix;
}
}
class SubClass2 extends AbstractClass{
public function abstractTest1(){
return "SubClass2";
}
public function abstractTest2($suffix){
return "SubClass2 ".$suffix;
}
}

$subclass1Instance=new SubClass1();
$subclass1Instance->display(); //Protected method can be called here.
echo "<br />";
echo $subclass1Instance->abstractTest2("Class1");
echo "<br />";
$subclass2Instance=new SubClass2();
echo $subclass2Instance->abstractTest1(); //As we declared public so can be access here.
echo "<br />";
echo $subclass2Instance->abstractTest2("Class2");

?>

An the output is,

SubClass1
SubClass1 Class1
SubClass2
SubClass2 Class2

Related Documents
http://arjudba.blogspot.com/2009/03/static-declaration-with-example-in-php.html
http://arjudba.blogspot.com/2009/03/class-concepts-and-usage-syntax-in-php.html
http://arjudba.blogspot.com/2009/03/class-inheritance-example-in-php.html
http://arjudba.blogspot.com/2009/03/autoloading-objects-in-php.html
http://arjudba.blogspot.com/2009/03/constructors-and-destructors-in-php.html

No comments:

Post a Comment