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.

Interface synopsis

Traversable

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

Changelog

Version Description
7.4.0 The Traversable interface can now be implemented by abstract classes. Extending classes must implement Iterator or IteratorAggregate.

Notes

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:

Prior to PHP 7.4.0, this internal engine interface couldn't be implemented in PHP scripts. Either IteratorAggregate or Iterator must be used instead.

The Iterator interface

Introduction

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

Interface synopsis

Iterator extends Traversable
/* Methods */
public mixed Iterator::current()
public mixed Iterator::key()
public void Iterator::next()
public void Iterator::rewind()
public bool Iterator::valid()

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(): void {
        
var_dump(__METHOD__);
        
$this->position 0;
    }

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

    #[
\ReturnTypeWillChange]
    public function 
key() {
        
var_dump(__METHOD__);
        return 
$this->position;
    }

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

    public function 
valid(): bool {
        
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"

See Also

See also object iteration.

The IteratorAggregate interface

Introduction

Interface to create an external Iterator.

Interface synopsis

IteratorAggregate extends Traversable
/* Methods */
public Traversable IteratorAggregate::getIterator()

Examples

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 
$property4 "";

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

    public function 
getIterator(): Traversable
    
{
        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"

The InternalIterator class

Introduction

Class to ease implementing IteratorAggregate for internal classes.

Class synopsis

final InternalIterator
implements Iterator
/* Methods */
private __construct()
public mixed current()
public mixed key()
public void next()
public void rewind()
public bool valid()

Throwable

Introduction

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

Note:

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

Interface synopsis

Throwable extends Stringable
/* Methods */
public string Throwable::getMessage()
public int Throwable::getCode()
public string Throwable::getFile()
public int Throwable::getLine()
public array Throwable::getTrace()
public string Throwable::getTraceAsString()
public Throwablenull Throwable::getPrevious()
public string Throwable::__toString()
/* Inherited methods */
public string Stringable::__toString()

Changelog

Version Description
8.0.0 Throwable implements Stringable now.

The ArrayAccess interface

Introduction

Interface to provide accessing objects as arrays.

Interface synopsis

ArrayAccess
/* Methods */
public bool ArrayAccess::offsetExists(mixed $offset)
public mixed ArrayAccess::offsetGet(mixed $offset)
public void ArrayAccess::offsetSet(mixed $offset, mixed $value)
public void ArrayAccess::offsetUnset(mixed $offset)

Examples

Example #1 Basic usage

<?php
class Obj implements ArrayAccess {
    public 
$container = [
        
"one"   => 1,
        
"two"   => 2,
        
"three" => 3,
    ];

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

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

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

    public function 
offsetGet($offset): mixed {
        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.

Warning

As of PHP 8.1.0, a class which implements Serializable without also implementing __serialize() and __unserialize() will generate a deprecation warning.

Interface synopsis

Serializable
/* Methods */
public stringnull Serializable::serialize()
public void Serializable::unserialize(string $data)

Examples

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 yield objects of this type. 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

final Closure
/* Methods */
private __construct()
public static Closurenull bind(Closure $closure, objectnull $newThis, objectstringnull $newScope = "static")
public Closurenull bindTo(objectnull $newThis, objectstringnull $newScope = "static")
public mixed call(object $newThis, mixed ...$args)
public static Closure fromCallable(callable $callback)

The stdClass class

Introduction

A generic empty class with dynamic properties.

Objects of this class can be instantiated with new operator or created by typecasting to object. Several PHP functions also create instances of this class, e.g. json_decode, mysqli_fetch_object or PDOStatement::fetchObject.

Despite not implementing __get()/__set() magic methods, this class allows dynamic properties and does not require the #[\AllowDynamicProperties] attribute.

This is not a base class as PHP does not have a concept of a universal base class. However, it is possible to create a custom class that extends from stdClass and as a result inherits the functionality of dynamic properties.

Class synopsis

stdClass

This class has no methods or default properties.

Examples

Example #1 Created as a result of typecasting to object

<?php
$obj 
= (object) array('foo' => 'bar');
var_dump($obj);

The above example will output:

object(stdClass)#1 (1) {
  ["foo"]=>
  string(3) "bar"
}

Example #2 Created as a result of json_decode

<?php
$json 
'{"foo":"bar"}';
var_dump(json_decode($json));

The above example will output:

object(stdClass)#1 (1) {
  ["foo"]=>
  string(3) "bar"
}

Example #3 Declaring dynamic properties

<?php
$obj 
= new stdClass();
$obj->foo 42;
$obj->{1} = 42;
var_dump($obj);

The above example will output:

object(stdClass)#1 (2) {
  ["foo"]=>
  int(42)
  ["1"]=>
  int(42)
}

The Generator class

Introduction

Generator objects are returned from generators.

Caution

Generator objects cannot be instantiated via new.

Class synopsis

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

See Also

See also object iteration.

The Fiber class

Introduction

Fibers represent full-stack, interruptible functions. Fibers may be suspended from anywhere in the call-stack, pausing execution within the fiber until the fiber is resumed at a later time.

Class synopsis

final Fiber
/* Methods */
public __construct(callable $callback)
public mixed start(mixed ...$args)
public mixed resume(mixed $value = null)
public mixed throw(Throwable $exception)
public mixed getReturn()
public bool isStarted()
public bool isSuspended()
public bool isRunning()
public bool isTerminated()
public static mixed suspend(mixed $value = null)
public static Fibernull getCurrent()

See Also

Fibers overview

The WeakReference class

Introduction

Weak references allow the programmer to retain a reference to an object which does not prevent the object from being destroyed. They are useful for implementing cache like structures.

WeakReferences cannot be serialized.

Class synopsis

final WeakReference
/* Methods */
public __construct()
public static WeakReference create(object $object)
public objectnull get()

WeakReference Examples

Example #1 Basic WeakReference Usage

<?php
$obj 
= new stdClass;
$weakref WeakReference::create($obj);
var_dump($weakref->get());
unset(
$obj);
var_dump($weakref->get());
?>

The above example will output something similar to:

object(stdClass)#1 (0) {
}
NULL

The WeakMap class

Introduction

A WeakMap is map (or dictionary) that accepts objects as keys. However, unlike the otherwise similar SplObjectStorage, an object in a key of WeakMap does not contribute toward the object's reference count. That is, if at any point the only remaining reference to an object is the key of a WeakMap, the object will be garbage collected and removed from the WeakMap. Its primary use case is for building caches of data derived from an object that do not need to live longer than the object.

WeakMap implements ArrayAccess, Traversable (via IteratorAggregate), and Countable, so in most cases it can be used in the same fashion as an associative array.

Class synopsis

final WeakMap
implements ArrayAccess Countable IteratorAggregate
/* Methods */
public int count()
public Iterator getIterator()
public bool offsetExists(object $object)
public mixed offsetGet(object $object)
public void offsetSet(object $object, mixed $value)
public void offsetUnset(object $object)

Examples

Example #1 Weakmap usage example

<?php
$wm 
= new WeakMap();

$o = new stdClass;

class 
{
    public function 
__destruct() {
        echo 
"Dead!\n";
    }
}

$wm[$o] = new A;

var_dump(count($wm));
echo 
"Unsetting...\n";
unset(
$o);
echo 
"Done\n";
var_dump(count($wm));

The above example will output:

int(1)
Unsetting...
Dead!
Done
int(0)

The Stringable interface

Introduction

The Stringable interface denotes a class as having a __toString() method. Unlike most interfaces, Stringable is implicitly present on any class that has the magic __toString() method defined, although it can and should be declared explicitly.

Its primary value is to allow functions to type check against the union type string|Stringable to accept either a string primitive or an object that can be cast to a string.

Interface synopsis

Stringable
/* Methods */
public string Stringable::__toString()

Stringable Examples

Example #1 Basic Stringable Usage

<?php
class IPv4Address implements Stringable {
    private 
string $oct1;
    private 
string $oct2;
    private 
string $oct3;
    private 
string $oct4;

    public function 
__construct(string $oct1string $oct2string $oct3string $oct4) {
        
$this->oct1 $oct1;
        
$this->oct2 $oct2;
        
$this->oct3 $oct3;
        
$this->oct4 $oct4;
    }

    public function 
__toString(): string {
        return 
"$this->oct1.$this->oct2.$this->oct3.$this->oct4";
    }
}

function 
showStuff(string|Stringable $value) {
    
// A Stringable will get converted to a string here by calling
    // __toString.
    
print $value;
}

$ip = new IPv4Address('123''234''42''9');

showStuff($ip);
?>

The above example will output something similar to:

123.234.42.9

The UnitEnum interface

Introduction

The UnitEnum interface is automatically applied to all enumerations by the engine. It may not be implemented by user-defined classes. Enumerations may not override its methods, as default implementations are provided by the engine. It is available only for type checks.

Interface synopsis

UnitEnum
/* Methods */
public static array UnitEnum::cases()

The BackedEnum interface

Introduction

The BackedEnum interface is automatically applied to backed enumerations by the engine. It may not be implemented by user-defined classes. Enumerations may not override its methods, as default implementations are provided by the engine. It is available only for type checks.

Interface synopsis

BackedEnum extends UnitEnum
/* Methods */
public static static BackedEnum::from(intstring $value)
public static staticnull BackedEnum::tryFrom(intstring $value)
/* Inherited methods */
public static array UnitEnum::cases()

The SensitiveParameterValue class

Introduction

The SensitiveParameterValue class allows wrapping sensitive values to protect them against accidental exposure.

Values of parameters having the SensitiveParameter attribute will automatically be wrapped inside of a SensitiveParameterValue object within stack traces.

Class synopsis

final SensitiveParameterValue
/* Properties */
private readonly mixed $value;
/* Methods */
public __construct(mixed $value)
public array __debugInfo()
public mixed getValue()

Properties

value

The sensitive value to be protected against accidental exposure.