PHP › Closures & Anonymous Functions

How can closures be used to implement simple dependency injection or callback based customization within a class?

Intermediate

Answer

A closure can be passed into a class constructor or method as a way to inject custom behavior without requiring a full separate class or interface implementation, letting the receiving class remain generic and reusable while still allowing calling code to customize exactly how a specific piece of logic, such as formatting output or filtering results, actually behaves for a particular use case.
class Report {
    private $formatter;
    public function __construct(callable $formatter) {
        $this->formatter = $formatter;
    }
    public function render($data) {
        return ($this->formatter)($data);
    }
}
Real-world example A reporting class accepts a formatting closure through its constructor, letting one part of the application generate a report formatted as plain text while another part generates the exact same underlying report data formatted as HTML, simply by passing a different closure.

Common follow-ups: What is the difference between accepting a closure and accepting an interface implementation for this kind of customization?;How does PHP's callable type hint work with closures?