php 魔术方法 call是什么
2022-12-02 09:01:16
194
{{single.collect_count}}

php __call是php魔术方法中的一个,当程序调用到当前类中未声明或没权限调用的方法时,就会调用__call方法。

php入门到就业线上直播课:进入学习
Apipost = Postman + Swagger + Mock + Jmeter 超好用的API调试工具:点击使用

本文操作环境:Windows7系统、PHP7.1版,DELL G3电脑

php魔术方法__call

__call是魔术方法中的一个,当程序调用到当前类中未声明或没权限调用的方法时,就会调用__call方法

class test{public function emptyFunc(){$getArgs = func_get_args();$funcName = $getArgs[0];//$params = array_slice($getArgs, 1);//var_dump($params);// this is paramsreturn $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 ′
登录后复制

,第二个params是调用'nowToTest'方法时传入的参数。以数组的形式组合在$params中。

call_user_func_array(method,method,params)这个php方法的作用是调用 method方法,参数为method方法,参数为params,如果方法是在类中的话,就用上面那种数组形式调用就可以了,这里调用的是emptyFunc方法。 func_get_args()的作用是以数组形式获取传入的所有参数。而这些参数在__call中传入的,第一个参数就是方法名。所以最后返回的结果是

"nowToTest function is not exists"
登录后复制

推荐学习:《PHP视频教程

以上就是php 魔术方法 call是什么的详细内容,更多请关注php中文网其它相关文章!

回帖
全部回帖({{commentCount}})
{{item.user.nickname}} {{item.user.group_title}} {{item.friend_time}}
{{item.content}}
{{item.comment_content_show ? '取消' : '回复'}} 删除
回帖
{{reply.user.nickname}} {{reply.user.group_title}} {{reply.friend_time}}
{{reply.content}}
{{reply.comment_content_show ? '取消' : '回复'}} 删除
回帖
收起
没有更多啦~
{{commentLoading ? '加载中...' : '查看更多评论'}}