谁能讲一下__call的用法呢?
Jun 06, 2016 pm 08:17 PM
__call只有两个参数吗?这个代码里面为什么传了好几个参数呢 这个怎么处理呢?
我看有人这么说 __call 第一个参数$m 就是你要调用的方法 test. 这句话我都理解不了 第一个参数不是1吗?
<code><?php class Caller { private $x = array(1, 2, 3); public function __call($m, $a) { print "Method $m called:n"; var_dump($a); return $this->x; } } $foo = new Caller(); $a = $foo->test(1, "2", 3.4, true); var_dump($a); ?></code>
回复内容:
__call只有两个参数吗?这个代码里面为什么传了好几个参数呢 这个怎么处理呢?
我看有人这么说 __call 第一个参数$m 就是你要调用的方法 test. 这句话我都理解不了 第一个参数不是1吗?
<code><?php class Caller { private $x = array(1, 2, 3); public function __call($m, $a) { print "Method $m called:n"; var_dump($a); return $this->x; } } $foo = new Caller(); $a = $foo->test(1, "2", 3.4, true); var_dump($a); ?></code>
__call
是调用未定义的方法时调用的。
也就是说,你的test
方法未定义,那么test
这个方法名就会作为__call
的第一个参数传入,而test
的参数会被装进数组中作为__call
的第二个参数传入。
所以当你调用$foo->test(1, "2", 3.4, true)
时,实际是相当于调用$foo->__call('test', array(1, "2", 3.4, true))
。
__call方法在调用类的方法时触发,比如:
<code><?php class google{ public function search(){ //TODO } public function __call($method, $parameters){ //这里的method便是对应的方法,即"->"后面的字符串,$parameters是通过这个方法传过来的参数 } } $google = new google(); $keyword = 'VR'; $google->search($keyword); //当调用当前对象不存在的方法时,会转向__call $google->operate();</code>
利用__call可以做些封装,从而调用其它对象和方法。
附官方参考:PHP魔术方法
第一个参数就是你调用的不存在的方法的函数名,第二个就是你调用的不存在的方法时传的一对参数

Heißer Artikel

Hot-Tools-Tags

Heißer Artikel

Heiße Artikel -Tags

Notepad++7.3.1
Einfach zu bedienender und kostenloser Code-Editor

SublimeText3 chinesische Version
Chinesische Version, sehr einfach zu bedienen

Senden Sie Studio 13.0.1
Leistungsstarke integrierte PHP-Entwicklungsumgebung

Dreamweaver CS6
Visuelle Webentwicklungstools

SublimeText3 Mac-Version
Codebearbeitungssoftware auf Gottesniveau (SublimeText3)

Heiße Themen

PHP 8.4 Installations- und Upgrade-Anleitung für Ubuntu und Debian

So richten Sie Visual Studio-Code (VS-Code) für die PHP-Entwicklung ein
