Home  >  Article  >  Backend Development  >  PHP中__call()方法详解

PHP中__call()方法详解

PHPz
PHPzOriginal
2016-06-13 11:45:018002browse

前面给大家介绍了《__construct(),类的构造函数》《__destruct(),类的析构函数》,下面继续给大家介绍PHP中__call()方法

__call(),在对象中调用一个不可访问方法时调用。

该方法有两个参数,第一个参数 $function_name 会自动接收不存在的方法名,第二个 $arguments 则以数组的方式接收不存在方法的多个参数。

1、 __call() 方法的格式:

function __call(string $function_name, array $arguments)
{
    // 方法体
}

2、 __call() 方法的作用:

为了避免当调用的方法不存在时产生错误,而意外的导致程序中止,可以使用 __call() 方法来避免。

该方法在调用的方法不存在时会自动调用,程序仍会继续执行下去。

请参考如下代码:

"; 
    }      
        
    /**
     * 声明此方法用来处理调用对象中不存在的方法
     */
    function __call($funName, $arguments)
    { 
          echo "你所调用的函数:" . $funName . "(参数:" ;  // 输出调用不存在的方法名
          print_r($arguments); // 输出调用不存在的方法时的参数列表
          echo ")不存在!
\n"; // 结束换行 } } $Person = new Person(); $Person->run("teacher"); // 调用对象中不存在的方法,则自动调用了对象中的__call()方法 $Person->eat("小明", "苹果"); $Person->say();

运行结果:

你所调用的函数:run(参数:Array ( [0] => teacher ) )不存在!
你所调用的函数:eat(参数:Array ( [0] => 小明 [1] => 苹果 ) )不存在!
Hello, world!
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