How to use PHP __call() Magic Method?

How to use PHP __call() Magic Method?

Posted on:April 10, 2023 at 10:00 AM

The PHP __call() magic method is an incredibly powerful tool for dynamic method handling and custom object behaviors. While its basic usage is well-known, there are many advanced techniques and real-life scenarios where the __call() method can be utilized to take your code to the next level. In this article, we’ll explore some of these advanced uses of the __call() method with real-life examples.

Imagine that you have class like this:

class MyClass {
    private string $foo;
    private string $bar;
    // You have few more private properties

    public function __construct(string $foo, string $bar){
        $this->foo = $foo;
        $this->bar = $bar;
    }

    public function getFoo(){
        return $this->foo;
    }

    public function getBar(){
        return $this->bar;
    }

    // You have few more getter methods
}

Now you can access like this way:

$object = new MyClass('Foo', 'Bar');

$object->foo();     // Foo
$object->bar();     // Bar

Definitely it will be a problem as long as your private properly increase that you want to access outside of the class. Therefore the __call() magic method exists to access.

How to use __call() magic method?

class MyClass {
    private string $foo;
    private string $bar;
    // You have few more private properties

    public function __construct(string $foo, string $bar){
        $this->foo = $foo;
        $this->bar = $bar;
    }

    public function __call($methodName, $arguments) {
        if (! property_exists($this, $methodName)) {
            throw new Exception("Bad Method Name Exception: $methodName");
        }

        return $this->$methodName;
    }
}

Now you can call exactly the same way and you will get the same result.

$object = new MyClass('Foo', 'Bar');

$object->foo();     // Foo
$object->bar();     // Bar

In this way, you can increase as many as private property you want. All will works fine as long as you use the same name for method and property.

Thanks :)