PHP › Magic Methods
What does the __call magic method do, and how can it be used to implement dynamic method handling for methods that are not explicitly defined on a class?
IntermediateAnswer
The __call magic method is automatically invoked whenever code attempts to call a method on an object that does not actually exist as a defined method, receiving the attempted method name and the arguments passed to it, which lets you implement dynamic behavior, such as automatically generating getter and setter methods on the fly, or building a fluent query builder that dynamically constructs method chains that were never individually predefined in the class.
class QueryBuilder {
private $conditions = [];
public function __call($name, $arguments) {
if (str_starts_with($name, 'where')) {
$field = strtolower(substr($name, 5));
$this->conditions[$field] = $arguments[0];
}
return $this;
}
}
$query = new QueryBuilder();
$query->whereName('Ali')->whereAge(30);Real-world example A custom query builder library uses __call to dynamically support methods like whereName or whereAge without needing to individually define every single possible field specific method in advance, generating that behavior dynamically instead.