PHP : Predefined Interfaces and Classes

Advance PHP consist of some interesting concepts. Let’s us learn them in this post


First of all. Let start with OOPS basics,

What is an Interface???

It is similar to class, it is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.

Along with abstract methods an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods.

Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements.

What is an class ?

In object-oriented programming , a class is a template definition of the methods and variables in a particular kind of object . Thus, an object is a specific instance of a class; it contains real values instead of variables.

So we have some predefined Interfaces and Classes in PHP, Like

The Traversable Interface :

In PHP, there is foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.

Traversable Interface to detect if a class is traversable using foreach.

Traversable is Abstract base interface that cannot be implemented alone. Instead it must be implemented by either IteratorAggregate or Iterator.

The Iterator Interface :

Iterator Interface extends the Traversable Interface.

Traversable Synopsis

Iterator extends Traversable {
/* Methods */
abstract public mixed current ( void )
abstract public scalar key ( void )
abstract public void next ( void )
abstract public void rewind ( void )
abstract public boolean valid ( void )

Iterator::current — Return the current element
Iterator::key — Return the key of the current element
Iterator::next — Move forward to next element
Iterator::rewind — Rewind the Iterator to the first element
Iterator::valid — Checks if current position is valid

PHP already provides a number of iterators for many day to day tasks. See SPL iterators for a list.

The IteratorAggregate interface :

IteratorAggregate Interface extends the Traversable Interface.

IteratorAggregate extends Traversable {
/* Methods */
abstract public Traversable getIterator ( void )

IteratorAggregate::getIterator — Retrieve an external iterator

Example how to use IteratorAggregate Interface

// IteratorAggregate
// Create indexed and associative arrays.

class myData implements IteratorAggregate {

    private $array = [];
    const TYPE_INDEXED = 1;
    const TYPE_ASSOCIATIVE = 2;

    public function __construct( array $data, $type = self::TYPE_INDEXED ) {
        while( list($k, $v) = each($data) ) {
            $type == self::TYPE_INDEXED ?
            $this->array[] = $v :
            $this->array[$k] = $v;

    public function getIterator() {
        return new ArrayIterator($this->array);


$obj = new myData(['one'=>'php','javascript','three'=>'c#','java',], /*TYPE 1 or 2*/ );

foreach($obj as $key => $value) {
    var_dump($key, $value);
    echo PHP_EOL;

// if TYPE == 1
#string(3) "php"
#string(10) "javascript"
#string(2) "c#"
#string(4) "java"

// if TYPE == 2
#string(3) "one"
#string(3) "php"
#string(10) "javascript"
#string(5) "three"
#string(2) "c#"
#string(4) "java"
The Throwable Interface

PHP 5 has an exception model similar to that of other programming languages. An exception can be thrown, and caught (“catched”) within PHP. Code may be surrounded in a try block, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch or finally block.

The thrown object must be an instance of the Exception class or a subclass of Exception. Trying to throw an object that is not will result in a PHP Fatal Error.

Exception is the base class for all Exceptions in PHP 5, and the base class for all user exceptions in PHP 7.

In PHP 7, Exception implements the Throwable interface.

Throwable is the base interface for any object that can be thrown via a throw statement in PHP 7, including Error and Exception.

Throwable Interface Synopsis

Throwable {
/* Methods */
abstract public string getMessage ( void )
abstract public int getCode ( void )
abstract public string getFile ( void )
abstract public int getLine ( void )
abstract public array getTrace ( void )
abstract public string getTraceAsString ( void )
abstract public Throwable getPrevious ( void )
abstract public string __toString ( void )

Exception implements Throwable Interface

Exception {
/* Properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
public __construct ([ string $message = "" [, int $code = 0 [, Throwable $previous = NULL ]]] )
final public string getMessage ( void )
final public Exception getPrevious ( void )
final public mixed getCode ( void )
final public string getFile ( void )
final public int getLine ( void )
final public array getTrace ( void )
final public string getTraceAsString ( void )
public string __toString ( void )
final private void __clone ( void )
 The ArrayAccess Interface:

Interface to provide accessing objects as an arrays

Interface Synopsis

ArrayAccess {
/* Methods */
abstract public boolean offsetExists ( mixed $offset )
abstract public mixed offsetGet ( mixed $offset )
abstract public void offsetSet ( mixed $offset , mixed $value )
abstract public void offsetUnset ( mixed $offset )

It consist of Abstract Method like

ArrayAccess::offsetExists — Whether an offset exists
ArrayAccess::offsetGet — Offset to retrieve
ArrayAccess::offsetSet — Assign a value to the specified offset
ArrayAccess::offsetUnset — Unset an offset

The Serializable Interface

This method is used for customized serializing.

Serializable {
/* Methods */
abstract public string serialize ( void )
abstract public void unserialize ( string $serialized )

The Closure Class

Class used to represent anonymous functions.

Now what is anonymous functions ???

Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses.

echo preg_replace_callback('~-([a-z])~', function ($match) {
    return strtoupper($match[1]);
}, 'hello-world');
// outputs helloWorld

Closures can also be used as the values of variables; PHP automatically converts such expressions into instances of the Closure internal class. Assigning a closure to a variable uses the same syntax as any other assignment, including the trailing semicolon:

$greet = function($name)
    printf("Hello %s\r\n", $name);


Closures Synopsis

Closure {
/* Methods */
private __construct ( void )
public static Closure bind ( Closure $closure , object $newthis [, mixed $newscope = "static" ] )
public Closure bindTo ( object $newthis [, mixed $newscope = "static" ] )
public mixed call ( object $newthis [, mixed $... ] )

Closure::__construct — Constructor that disallows instantiation
Closure::bind — Duplicates a closure with a specific bound object and class scope
Closure::bindTo — Duplicates the closure with a new bound object and class scope
Closure::call — Binds and calls the closure

Example to delete a directory with all subdirectories and files:

$deleteDirectory = null;
$deleteDirectory = function($path) use (&$deleteDirectory) {
    $resource = opendir($path);
    while (($item = readdir($resource)) !== false) {
        if ($item !== "." && $item !== "..") {
            if (is_dir($path . "/" . $item)) {
                $deleteDirectory($path . "/" . $item);
            } else {
                unlink($path . "/" . $item);

The Generator Class

It return generator object

Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface.

A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate. Instead, you can write a generator function, which is the same as a normal function, except that instead of returning once, a generator can yield as many times as it needs to in order to provide the values to be iterated over.

A simple example of this is to re-implement the range() function as a generator. The standard range() function has to generate an array with every value in it and return it, which can result in large arrays: for example, calling range(0, 1000000) will result in well over 100 MB of memory being used.

Fibonacci generator:

function fib($n)
    $cur = 1;
    $prev = 0;
    for ($i = 0; $i < $n; $i++) {
        yield $cur;

        $temp = $cur;
        $cur = $prev + $cur;
        $prev = $temp;

$fibs = fib(9);
foreach ($fibs as $fib) {
    echo " " . $fib;

// prints: 1 1 2 3 5 8 13 21 34

Hope you like this post. Please do share you reviews in below comments section

1 thought on “PHP : Predefined Interfaces and Classes”

Leave a Reply