Home >Backend Development >PHP Tutorial >php object-oriented OOP—__call handles calling errors
In program development, if when using an object to call an internal method of the object, the called method does not exist, then the program will error, and then the program will exit and cannot continue to execute. So when the program calls a method that does not exist inside the object, can we be prompted that the method called and the parameters used do not exist, but the program can continue to execute. At this time, we have to use the method that is automatically called when calling the method that does not exist. Method "__call()".
//This is a test class, there are no attributes and methods in it
class Test
{
}
//Generate an object of Test class
$test = new Test();
/ /Call a method that does not exist in the object
$test->demo("one", "two", "three");
//The program will not execute here
echo "this is a test
";
?>
The following error occurs in the above example, and the program usually cannot continue to execute;
class Test
{
//Method that is automatically called when a non-existing method is called, no. One parameter is the method name, and the second parameter is the array parameter
function __call($function_name, $args) {
print "The function you called: $function_name(parameters: ";
print_r( $args);
echo ") does not exist!
";
}
}
//Generate an object of Test class
$test=new Test();
//In the calling object Non-existent method
$test->demo("one", "two", "three");
//The program will not exit and can be executed here
echo "this is a test
";
? >
The output result of the above example is:
The function you called: demo (parameter: Array ([0] => one [1] => two [2] => three )) does not exist!
this is a test
"Brother, thank you for sharing.