Home>Article>Backend Development> How to use php call method

How to use php call method

藏色散人
藏色散人 Original
2020-08-08 10:34:34 3569browse

php call method refers to the "__call()" magic method, which is called when an inaccessible method is called in the object. The format of the call method is "function __call(string $function_name,array $arguments){ Method body}".

How to use php call method

Recommended: "PHP Video Tutorial"

__call(), when calling an inaccessible method in an object transfer.

This method has two parameters. The first parameter $function_name will automatically receive the non-existing method name, and the second $arguments will receive multiple parameters of the non-existing method in the form of an array.

1. The format of the __call() method:

function __call(string $function_name, array $arguments){ // 方法体}

2. The function of the __call() method:

In order to avoid errors when the called method does not exist, Accidentally causing the program to terminate can be avoided by using the __call() method.

This method will be automatically called when the called method does not exist, and the program will continue to execute.

Please refer to the following code:

"; } /** * 声明此方法用来处理调用对象中不存在的方法 */ function __call($funName, $arguments) { echo "你所调用的函数:" . $funName . "(参数:" ; // 输出调用不存在的方法名 print_r($arguments); // 输出调用不存在的方法时的参数列表 echo ")不存在!
\n"; // 结束换行 } } $Person = new Person(); $Person->run("teacher"); // 调用对象中不存在的方法,则自动调用了对象中的__call()方法$Person->eat("小明", "苹果"); $Person->say();

Running result:

你所调用的函数:run(参数:Array ( [0] => teacher ) )不存在! 你所调用的函数:eat(参数:Array ( [0] => 小明 [1] => 苹果 ) )不存在! Hello, world!

The above is the detailed content of How to use php call method. For more information, please follow other related articles on the PHP Chinese website!

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