Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

C - Built-in Interfaces and Magic Methods

Two reference tables: the SPL interfaces that let your objects plug into PHP’s built-in language features, and the magic methods that let your objects hook into behavior PHP would otherwise handle for you.

Built-in interfaces

InterfaceImplementing it gets you
CountableYour objects work with count()
ArrayAccessYour objects support $obj[$key] syntax: read, write, isset, and unset
IteratorYour objects work directly in foreach, with full control over the iteration
IteratorAggregateYour objects work in foreach by delegating to another iterator, usually a Generator
StringableYour objects can be used anywhere a string is expected

Stringable is the odd one out: it was added in PHP 8, and you rarely need to implement it explicitly, since any class that defines __toString() is automatically treated as implementing it. It exists mostly so type declarations can say “anything printable,” rather than listing every class that happens to have a __toString() method.

Full examples of all five, including what Iterator demands of you that IteratorAggregate doesn’t, are in Chapter 20.

Magic methods

MethodCalled when
__constructAn object is created
__destructAn object is about to be destroyed
__getReading an inaccessible or undefined property
__setWriting to an inaccessible or undefined property
__callCalling an inaccessible or undefined instance method
__callStaticCalling an inaccessible or undefined static method
__toStringThe object is used in a string context
__invokeThe object is called as if it were a function
__cloneThe object is duplicated with clone

“Magic” is PHP’s word for methods the language calls for you, by naming convention, rather than you calling directly. Useful for building things like lazy-loaded properties or fluent proxies, easy to overuse into code nobody can trace by reading it. Full treatment, with the tradeoffs, in Chapter 17.