How to use php call method

藏色散人
Release: 2023-03-04 07:02:01
Original
3636 people have browsed it

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){    // 方法体}
Copy after login

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:

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

Running result:

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!