Home  >  Article  >  Backend Development  >  谁能讲一下__call的用法呢?

谁能讲一下__call的用法呢?

WBOY
WBOYOriginal
2016-06-06 20:17:111303browse

__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魔术方法

第一个参数就是你调用的不存在的方法的函数名,第二个就是你调用的不存在的方法时传的一对参数

Statement:
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