Predefined Interfaces and Classes

Table of Contents

See also the SPL Interfaces and reserved classes.

The Traversable interface

Introduction

Interface to detect if a class is traversable using foreach.

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

Note:

Internal (built-in) classes that implement this interface can be used in a foreach construct and do not need to implement IteratorAggregate or Iterator.

Note:

This is an internal engine interface which cannot be implemented in PHP scripts. Either IteratorAggregate or Iterator must be used instead. When implementing an interface which extends Traversable, make sure to list IteratorAggregate or Iterator before its name in the implements clause.

Interface synopsis

Traversable
class Traversable {
}

This interface has no methods, its only purpose is to be the base interface for all traversable classes.

The Iterator interface

Introduction

Interface for external iterators or objects that can be iterated themselves internally.

Interface synopsis

Iterator
class 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 )
}

Predefined iterators

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

Examples

Example #1 Basic usage

This example demonstrates in which order methods are called when using foreach with an iterator.

<?php
class myIterator implements Iterator {
    private 
$position 0;
    private 
$array = array(
        
"firstelement",
        
"secondelement",
        
"lastelement",
    );  

    public function 
__construct() {
        
$this->position 0;
    }

    public function 
rewind() {
        
var_dump(__METHOD__);
        
$this->position 0;
    }

    public function 
current() {
        
var_dump(__METHOD__);
        return 
$this->array[$this->position];
    }

    public function 
key() {
        
var_dump(__METHOD__);
        return 
$this->position;
    }

    public function 
next() {
        
var_dump(__METHOD__);
        ++
$this->position;
    }

    public function 
valid() {
        
var_dump(__METHOD__);
        return isset(
$this->array[$this->position]);
    }
}

$it = new myIterator;

foreach(
$it as $key => $value) {
    
var_dump($key$value);
    echo 
"\n";
}
?>

The above example will output something similar to:

string(18) "myIterator::rewind"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(0)
string(12) "firstelement"

string(16) "myIterator::next"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(1)
string(13) "secondelement"

string(16) "myIterator::next"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(2)
string(11) "lastelement"

string(16) "myIterator::next"
string(17) "myIterator::valid"

The IteratorAggregate interface

Introduction

Interface to create an external Iterator.

Interface synopsis

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

Example #1 Basic usage

<?php
class myData implements IteratorAggregate {
    public 
$property1 "Public property one";
    public 
$property2 "Public property two";
    public 
$property3 "Public property three";

    public function 
__construct() {
        
$this->property4 "last property";
    }

    public function 
getIterator() {
        return new 
ArrayIterator($this);
    }
}

$obj = new myData;

foreach(
$obj as $key => $value) {
    
var_dump($key$value);
    echo 
"\n";
}
?>

The above example will output something similar to:

string(9) "property1"
string(19) "Public property one"

string(9) "property2"
string(19) "Public property two"

string(9) "property3"
string(21) "Public property three"

string(9) "property4"
string(13) "last property"

Throwable

Introduction

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

Note:

PHP classes cannot implement the Throwable interface directly, and must instead extend Exception.

Interface synopsis

Throwable
class 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 )
}

The ArrayAccess interface

Introduction

Interface to provide accessing objects as arrays.

Interface synopsis

ArrayAccess
class 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 )
}

Example #1 Basic usage

<?php
class obj implements ArrayAccess {
    private 
$container = array();

    public function 
__construct() {
        
$this->container = array(
            
"one"   => 1,
            
"two"   => 2,
            
"three" => 3,
        );
    }

    public function 
offsetSet($offset$value) {
        if (
is_null($offset)) {
            
$this->container[] = $value;
        } else {
            
$this->container[$offset] = $value;
        }
    }

    public function 
offsetExists($offset) {
        return isset(
$this->container[$offset]);
    }

    public function 
offsetUnset($offset) {
        unset(
$this->container[$offset]);
    }

    public function 
offsetGet($offset) {
        return isset(
$this->container[$offset]) ? $this->container[$offset] : null;
    }
}

$obj = new obj;

var_dump(isset($obj["two"]));
var_dump($obj["two"]);
unset(
$obj["two"]);
var_dump(isset($obj["two"]));
$obj["two"] = "A value";
var_dump($obj["two"]);
$obj[] = 'Append 1';
$obj[] = 'Append 2';
$obj[] = 'Append 3';
print_r($obj);
?>

The above example will output something similar to:

bool(true)
int(2)
bool(false)
string(7) "A value"
obj Object
(
    [container:obj:private] => Array
        (
            [one] => 1
            [three] => 3
            [two] => A value
            [0] => Append 1
            [1] => Append 2
            [2] => Append 3
        )

)

The Serializable interface

Introduction

Interface for customized serializing.

Classes that implement this interface no longer support __sleep() and __wakeup(). The method serialize is called whenever an instance needs to be serialized. This does not invoke __destruct() or have any other side effect unless programmed inside the method. When the data is unserialized the class is known and the appropriate unserialize() method is called as a constructor instead of calling __construct(). If you need to execute the standard constructor you may do so in the method.

Note, that when an old instance of a class that implements this interface now, which had been serialized before the class implemeted the interface, is unserialized, __wakeup() is called instead of the serialize method, which might be useful for migration purposes.

Interface synopsis

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

Example #1 Basic usage

<?php
class obj implements Serializable {
    private 
$data;
    public function 
__construct() {
        
$this->data "My private data";
    }
    public function 
serialize() {
        return 
serialize($this->data);
    }
    public function 
unserialize($data) {
        
$this->data unserialize($data);
    }
    public function 
getData() {
        return 
$this->data;
    }
}

$obj = new obj;
$ser serialize($obj);

var_dump($ser);

$newobj unserialize($ser);

var_dump($newobj->getData());
?>

The above example will output something similar to:

string(38) "C:3:"obj":23:{s:15:"My private data";}"
string(15) "My private data"

The Closure class

Introduction

Class used to represent anonymous functions.

Anonymous functions, implemented in PHP 5.3, yield objects of this type. This fact used to be considered an implementation detail, but it can now be relied upon. Starting with PHP 5.4, this class has methods that allow further control of the anonymous function after it has been created.

Besides the methods listed here, this class also has an __invoke method. This is for consistency with other classes that implement calling magic, as this method is not used for calling the function.

Class synopsis

Closure
class 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 $... ] )
public static Closure fromCallable ( callable $callable )
}

The Generator class

Introduction

Generator objects are returned from generators.

Caution

Generator objects cannot be instantiated via new.

Class synopsis

Generator
class Generator implements Iterator {
/* Methods */
public mixed current ( void )
public mixed getReturn ( void )
public mixed key ( void )
public void next ( void )
public void rewind ( void )
public mixed send ( mixed $value )
public mixed throw ( Throwable $exception )
public bool valid ( void )
public void __wakeup ( void )
}