Abstraction and Interface in PHP




In inheritance, we see that child class is taking properties from parent class and child class is independent of parent class.

Sometimes it's good to be able to lay down some ground rules about how a child class should behave. Abstract class and functions do this work. An abstract class contains some incomplete (abstract) function(s) which child class has to fulfilled for being a whole class otherwise child class will also be an abstract class.

<?php
// defining an abstract class
abstract class AbsClass
{
 function __construct()
 {
  echo "this is an abstract class <br>";
 }
 // abstract function
 abstract public function abs_function();
 function full_function()
 {
  echo "this is not an abstract function <br>";
 }
}
class SubClass extends AbsClass
{
 function __construct()
 {
  echo "this is child class <br>";
  parent::full_function();
 }
 // completing the abstruct function
 public function abs_function()
 {
  echo "this is completed abstract function <br>";
 }
}
$obj = new SubClass();
$obj->abs_function();
?>

  • We can not call abstract class. An abstract class can only be extended.
  • Sub class can still use its properties.
  • An abstract class is used to restrict sub class and for separating interface from implementation.

Interface:

Interface is a collection of abstract functions. A class can implement more than one interface. Class, which is implementing any interface, must implement all functions of the interface. Complete image of interface is:

<?php
// defining an interface
interface MyInterface
{
 // abstract functions 
 // all must be public
 public function display();
 public function another($argument);
}
// another interface
interface AnotherInterface
{
 public function complete_it();
 public function one_more();
}
class Parent
{
 function parent_fun()
 {
  echo "parent function";
 }
}
// class extending parent and implementing both interfaces
class Demo extends Parent implements MyInterface, AnotherInterface
{
 public function display()
 {
  echo "display complete";
 }
 public function another($argument)
 {
  #code
 }
 public function complete_it()
 {
  #code
 }
 public function one_more()
 {
  #code
 }
}
?>
  • All function inside the interface must be public.
  • A class can extend another class and also implement some interface. Class must declare parent class before interfaces.




Related Post


Latest Post


Recent Posts Widget

Make sure to never miss a thing...

Get the latest news from the creative industry along with other creative goodies, conveniently delivered to social media.