Abstract Classes and Interface in PHP

Abstract Classes and Interface in PHP

Today we discussed Abstract Classes and Interface in PHP Data abstraction first what is abstraction. As from name it seem like something that is hidden.  Yes nature of the abstract classes are same.Abstract classes are those classes which can not be directly initialized. Or in other word we can say that you can not create object of abstract classes.

Abstract Classes and Interface in PHP
Abstract Classes and Interface in PHP
  1. What is abstract classes.
  2. What is interface
  3. How to implement abstract classes in php
  4. How to implement interface in php
  5. Different between abstract classes and interface.
What is abstract Classes

 Abstract classes always created for inheritance purpose. You can only inherit abstract class in your child class. Lots of people say that in abstract class at least your one method should be abstract. Abstract method are the method which is only defined but declared. This is not true definition as per my assumption. But your any class has at least one method abstract than your class is abstract class.Usually abstract class are also known as base class. We call it base class because abstract class are not the class which is available directly for creating object. It can only act as parent class of any normal class. You can use abstract class in class hierarchy. Mean one abstract class can inherit another abstract class also.



Abstract classes in PHP

Abstract Classes and Interface in PHP
Abstract Classes and Interface in PHP

Abstract classes in php are simillar like other oop languages. You can create abstract classes in php using abstract keyword. Once you will make any class abstract in php you can not create object of that class.



abstract class abc
{
public function xyz()
{
return 1;
}
}
$a = new abc();//this will throw error in php
abstract class testParent
{
public function abc()
{
//body of your funciton
}
}
class testChild extends testParent
{
public function xyz()
{
//body of your function
}
}
$a = new testChild();



Implementation of abstract method



abstract class abc

{

abstract protected function f1($a , $b);

}

class xyz extends abc

{

protected function f1($name , $address)

{

echo "$name , $address";

}

}

$a = new xyz();
abstract class parentTest
{
abstract protected function f1();
abstract public function f2();
//abstract private function f3(); //this will trhow error
}
class childTest
{
public function f1()
{
//body of your function
}
public function f2()
{
//body of your function
}
protected function f3()
{
//body of your function
}
}
$a = new childTest();








Abstract Classes and Interface in PHP Dev2Tricks 5 of 5
Abstract Classes and Interface in PHP Today we discussed Abstract Classes and Interface in PHP Data abstraction first what is abstractio...

Share this

Related Posts

Previous
Next Post »