How to use __call() and __callStatic() in PHP

小云云
Release: 2023-03-22 09:58:02
Original
2073 people have browsed it

This article mainly shares with you how to use __call() and __callStatic() in PHP. I hope it can help you. I won’t explain too much about the use of these two methods. Through the example code and results, everyone can understand the functions of the two more clearly.

1.__call() method. When calling a method that is not declared in the class, you can call the __call() method instead of declaring a method. Accepts method name and array as parameters.

Code example:

<?php  
class test{  
//魔术方法__call  
/* 
$method 获得方法名 
$arg 获得方法的参数集合 
*/  
public function __call($method,$arg){  
    echo &#39;你想调用我不存在的方法&#39;,$method,&#39;方法<br/>&#39;;  
    echo &#39;还传了一个参数<br/>&#39;;  
    echo print_r($arg),&#39;<br/>&#39;;  
  }   
$list=new test();  
$list->say(1,2,3);  
  
?>
Copy after login

Execution result:

You want to call my non-existent method say method
also passed it One parameter
Array ([0] => 1 [1] => 2 [2] => 3 )

##2.__callStatic ()method. This method has appeared since PHP5.3 and is used when creating a static method to call a method that does not exist in the class. Same as the __call() method, accepting method name and array as parameters.

Code example:

<?php  
class test{  
//魔术方法__callStatic 
/* 
$method 获得方法名 
$arg 获得方法的参数集合 
*/  
//魔术方法__callStatic  
public static function __callStatic($method,$arg){  
  
    echo &#39;你想调用我不存在的&#39;,$method,&#39;静态方法<br/>&#39;;  
    echo &#39;还传了一个参数<br/>&#39;;  
    echo print_r($arg),&#39;<br/>&#39;;  
  }  
  
}  
test::cry(&#39;痛哭&#39;,&#39;鬼哭&#39;,&#39;号哭&#39;);  

?>
Copy after login
Execution result:


You want to call my non-existent cry static method
Also passed a parameter
Array ([0] => Cry[1] => Ghost cry[2] => Cry)

Related recommendations:

How to use the __call() method in php and overloading example analysis

php magic function __call() usage example analysis_PHP tutorial

Detailed explanation of php's magic methods __get(), __set(), __call(), __callStatic() and static usage

The above is the detailed content of How to use __call() and __callStatic() in PHP. 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!