Home >Backend Development >PHP Tutorial >php object-oriented OOP—__call handles calling errors

php object-oriented OOP—__call handles calling errors

WBOY
WBOYOriginal
2016-08-08 09:23:06950browse

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;

Fatal error: Call to undefined method Test::demo()

Next we add the "__call()" method. This method has 2 parameters. The first parameter is the process of calling a method that does not exist. , when automatically calling the __call() method, pass the method name of the non-existent method to the first parameter, The second parameter is to pass in the multiple parameters of this method in the form of an array.

//This is a test class, there are no attributes and methods in it
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.

The above introduces the PHP object-oriented OOP-__call handling calling errors, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn