What is the php magic method call?

藏色散人
Release: 2023-03-10 06:02:02
Original
2391 people have browsed it

php __call is one of the PHP magic methods. When the program calls a method that is not declared or has no permission to call in the current class, the __call method will be called.

What is the php magic method call?

The operating environment of this article: Windows7 system, PHP7.1 version, DELL G3 computer

php magic method __call

__call is one of the magic methods. When the program calls a method that is not declared or has no permission to call in the current class, the __call method

class test { public function emptyFunc(){ $getArgs = func_get_args(); $funcName = $getArgs[0]; //$params = array_slice($getArgs, 1); //var_dump($params); // this is params return $funcName . ' function is not exists'; } public function __call($m, $params) { $arr[] = $m; $arr = array_merge($arr, $params); return call_user_func_array(array($this, 'emptyFunc'), $arr); } protected function nowToTest(){ return 'this is nowToTest'; } } $testObj = new test(); var_dump($testObj->nowToTest('params1','params1')); //var_dump result => string(29) "nowToTest function is not exists" 如上test类中,nowToTest方法是存在的,但修饰这方法的是protected(保护),所以实例出来的对象没权限执行,这时就跑到__call中去了. _call()有2个参数,第一个m是当前调用方法的名字,这里是'nowToTest',第二个m是当前调用方法的名字,这里是 ′ nowToTest ′
Copy after login

will be called. The second params is Parameters passed in when calling the 'nowToTest' method. Combined in $params as an array.

The function of the call_user_func_array(method, method, params) php method is to call the method method. The parameter is the method method and the parameter is params. If the method is in the class, just use the above array form to call it. Okay, the emptyFunc method is called here. The function of func_get_args() is to get all the parameters passed in in the form of an array. When these parameters are passed in __call, the first parameter is the method name. So the final result returned is

"nowToTest function is not exists"
Copy after login

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of What is the php magic method call?. 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
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!