gpt4 book ai didi

php - __call() 方法说明

转载 作者:行者123 更新时间:2023-12-02 14:01:02 25 4
gpt4 key购买 nike

我有这部分代码:

class FTPClient
{
public function __construct() {
$args_num=func_num_args();
echo $args_num;
$this->{"__construct".($args_num===0 ? '' : $args_num)}(func_get_args());
}

function __call($name,$args) {
echo $name,count($args),'<br/>';
}

public function open() {
echo 'open';
}
}
$o = new FTPClient('127.0.0.1','user','pass');
$o = new FTPClient();
$o = new FTPClient('127.0.0.1','user');
$o->close();

输出如下所示:

3__construct3101__construct11 //Don't understand how this output came together?!2__construct21close0

有人可以帮我解释一下这个输出的第二行吗?

最佳答案

  1. 第一个示例

    $o = new FTPClient('127.0.0.1','user','pass');

    You have 3 arguments, means 3 gets printed with this line:

    $args_num = func_num_args();echo $args_num;  //output: 3

    After that you are trying to call the method __construct3():

    $this->__construct3(func_get_args());

    Which is not accessible, means __call() gets called. In that magic method you print the name, here __construct3 and the count of the arguments, here the argument array, means 1.

    Output:

    3__construct31
  2. 第二个示例

    $o = new FTPClient();

    You have 0 arguments, means 0 gets printed with this line:

    $args_num = func_num_args();echo $args_num;  //output: 0

    After that you are trying to call the method __construct(), the constructor:

    $this->__construct(func_get_args());

    And the constructor is callable, so __call() won't get called here. Instead the constructor gets called again, but with an array, which holds the array of arguments, here an empty array.

    Now in the second call you have 1 argument, means 1 gets printed with this line:

    $args_num = func_num_args();echo $args_num;  //output: 1

    After that you are trying to call the method __construct1():

    $this->__construct1(func_get_args());

    Now __construct1() is not accessible, means __call() gets triggered. In that magic method you print the name, here __construct1 and the count of the arguments, here an array with the argument array, means 1.

    Output:

    01__construct11

注释:

  • __call()当您尝试调用无法访问的方法时会被触发。

关于php - __call() 方法说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32703965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com