Skip to content

Chapter 7 of 7

Closures, Generators, and Magic Methods

Closures are anonymous functions that you can assign to variables, pass as arguments, or return from other functions. A regular closure captures variables from its enclosing scope through the use clause, and by default those variables are copied; prefixing them with an ampersand passes them by reference so the closure can mutate the original. Arrow functions, introduced in PHP 7.4, offer a more concise alternative: written as fn($x) => $x * 2, they automatically capture surrounding variables by value and must contain only a single expression, making them ideal for short transformations like those passed to array_map().

Generators provide a memory-efficient way to work with large or infinite sequences. A generator is simply a function that uses the yield keyword instead of return, emitting one value at a time and pausing execution between yields until the caller asks for the next item. You consume a generator with a foreach loop, which handles the iteration implicitly, or manually by calling current() and next() on the generator object itself. Generators implement the Iterator interface, and because they compute values lazily, they avoid holding entire datasets in memory. You can also yield key-value pairs with the syntax yield $key => $value; to produce associative results.

PHP offers a set of magic methods that hook into the language's built-in behaviors. __toString() runs when an object is used in a string context, allowing you to define how it should be represented. __get() and __set() intercept reads and writes to inaccessible properties, enabling property overloading for things like dynamic configuration objects. __invoke() lets an object be called like a function, treating an instance as a callable. Finally, __destruct() runs when an object is destroyed or goes out of scope, providing a hook for cleanup tasks such as closing file handles, although relying on it for critical logic is discouraged because destruction timing is not guaranteed. Together, these magic methods, combined with closures, generators, and static class members, give PHP developers a rich toolkit for building expressive and efficient applications.

All chapters
  1. 1Object-Oriented Foundations
  2. 2Inheritance, Interfaces, and Traits
  3. 3Namespaces and Dependency Management
  4. 4The PHP Type System
  5. 5Working with Arrays and Strings
  6. 6Databases, Sessions, and Error Handling
  7. 7Closures, Generators, and Magic Methods

Drill it

Reading is not remembering. These come from the Php Programming deck:

Q

What is a class in PHP OOP?

A class is a blueprint for creating objects. It defines properties (variables) and methods (functions) that the objects will have.class User { public string $na...

Q

What is the difference between public, protected, and private visibility in PHP?

public – accessible from anywhere.protected – accessible within the class and its subclasses.private – accessible only within the defining class.These are known...

Q

How do you create an object from a class in PHP?

Use the new keyword:$user = new User();This calls the class constructor (__construct) if one is defined.

Q

What is the purpose of the __construct() magic method?

__construct() is the constructor that runs automatically when an object is created with new.public function __construct(public string $name) {}It initializes ob...