__call() Magic Method

(2018)

class Car {
    public function __call($method, $args) {
        echo("MAGIC: $method\n");
    }
}

$car = new Car();
$car->drive(); // prints "drive"
$car->stop(); // prints "MAGIC: stop"

This can be used in a couple of neat ways, for example, you could do a twist on the Factory Pattern:

class Vehicle {
    public function getName() {
        return 'generic vehicle';
    }
}

class Bicycle {
    public function getName() {
        return 'bicycle';
    }
}
class FunkyFactory {

    public function __callStatic($method, $args) {
        if ('make' == substr($method, 4) {
            $class = substr($method, 4);
            return new $class($args);
        }
    }
}

FunkyFactory::makeBicycle()->getName(); // bicycle
FunkyFactory::makeVehicle()->getName(); // vehicle

Is that really any better than the less fanciful version?

FunkyFactory::make('Bicycle')

Not necessarily, but it can be more expressive, particularly in cases with multiple arguments or method chaining.

When used judiciously, magic methods are pretty cool and they can improve the code. But it's also easy to get too magical and make the code different to reason about.