Magic Methods in Php – __call() method

When to use the magic method __call(). ?
The magic method __call() is to undeclared methods what __get() and __set() are to undeclared data member.
These methods are automatically called internally when the program tires to execute a method that has not been defined within the class at the time of development.

The magic method __call() takes two arguments. The first argument is the name of the undeclared method invoked by the program and the second is an array that contains a list of parameters passed to the undeclared array.

Look at the example below:
class Customer {
 
 public function __call($name, $args) {
  var_dump($name);
  echo "\n";
  var_dump($args);
  echo "\n";
 }
}
 
$c = new Customer();
$c->setName("Hiren","Prajapati");
Output:
string(7) "setName"
array(2) {
[0]=>
string(5) "Hiren"
[1]=>
string(6) "Prajapati"
}
In the example above, an object of the Customer class is created and an undeclared method viz. $c->setName is called. The magic method __call() is internally executed which accepts two parameters. The first parameter $name contains the name of the method i.e. setName and the second parameter $args contains the arguments passed to the setName method i.e Hiren &Prajapati.
Using this method, you can provide code to handle calls to undeclared method. To disallow programs to call an undeclared method, you should raise an exception from within __call() magic method.
Look at the example below:
class Customer {
 
 public function __call($name, $args) {
  throw new Exception("Undeclared method execution not allowed",10);
 }
}
 
$c = new Customer();
$c->setName("Hiren","Prajapati");
Output:

Fatal error: Uncaught exception Exception with message "Undeclared method execution not allowed in .....":6
Stack trace:
#0 [internal function]: Customer->__call("setName", Array)
#1 ......(11): Customer->setName("Hiren","Prajapati")
#2 {main}
thrown in ..... on line 6

In the above program, when the script calls an undeclared variable $c->setName(), the magic method __call() is executed. On executing the magic method __call(), an exception is raised and the execution of the program stops there (unless we use the try..catch statements)

No comments: