PHP

PHP Class abstraction and Interfaces

Class-abstraction-&-Interfaces
Class-abstraction-&-Interfaces

Class Abstraction
=================

PHP 5 introduces abstract classes and methods. It is not allowed to create an instance of a class that has been defined as abstract. Any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method’s signature they cannot define the implementation.

When inheriting from an abstract class, all methods marked abstract in the parent’s class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.

<?php
abstract class AbsClass
{
public $a=10,$b=20;
function addNum($x=0,$y=0)
{
echo "Sum = ".($x+$y)."<br>";
}
abstract function subNum($x=0,$y=0);
}
?>
<?php
class AbsImpl extends AbsClass
{
function subNum($x=0,$y=0)
{
echo "Diff = ".($x-$y);
}
}
?>
<?php
echo "<h1>";
$obj=new AbsImpl();
$obj->addNum(10,20);
$obj->subNum(11,22);
?>

Interfaces
==========

Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.

Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined.

All methods declared in an interface must be public, this is the nature of an interface.

To implement an interface, the implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma.

interface Inter1

{

}

You Might Also Like