The call() magic method allows us to overload calling of methods that doesn't exists.

Let’s take a look at few examples to get a better understanding of what __call() magic method is capable of.

Simple Example

class DevPeel
{
	public function __call($name,$arguments){
		var_dump($name,$arguments);
	}
}

$class = new DevPeel();

$class->someMethod('param1',2);

In this example, as you can clearly see, we’re trying to call someMethod() on DevPeel class which doesn’t exist yet we’re able to call it using __call() magic method. __call() magic method takes two parameters, $name of the method & $arguments that method would take. We’re dumping results on $name & $arguments and can see the following output.

string(10) "someMethod"
array(2) {
  [0]=>
  string(6) "param1"
  [1]=>
  int(2)
}

Another Example (Choosing Mailer)

interface MailerInterface
{
	public function send();
}

class localSmtpMailer implements MailerInterface
{
	public function send(){
		var_dump('sent from local');
	}
}

class MailGunMailer implements MailerInterface
{
	public function send(){
		var_dump('sent from mailgun');
	}
}

class MailDecorator
{
	protected $mailer;
	public function __construct(MailerInterface $mailer){
		$this->mailer = $mailer;
	}

	public function __call($name,$arguments){
		return $this->mailer->{$name}($arguments);
	}


}

$mail = new MailDecorator(new MailGunMailer());
$mail->send();

Here we have a scenario where we’d like to use couple of mail servers and can choose between them within our application if required to. Here MailDecorator is responsible for choosing the mailer for us and will help in sending out the email and we’re making it possible using __call() magic method. As you can clearly see send() method is not available on MailDecorator class but __call() magic method allows us to overload calling the send() method here.

Another Example (Dynamic Methods)

class Builder
{
	public function where($key,$value){
		var_dump($key,$value);
	}

	public function __call($name,$arguments){
		$key = strtolower(str_replace('where', '', $name));

		return $this->where($key,$arguments[0]);
	}
}

$builder = new Builder();
$builder->whereEmail('usama@devpeel.com');

This example is inspired by Laravel query builder where we use dynamic methods like where{property} and it all works magically. So here we’ve tried to implement the basic functionality of how it actually works using __call() magic method.

You may also Like