PHP魔术方法__call()

2018-09-15 19:00 By "Powerless" 3020 0 0

__call()方法的用法

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

程序中调用未定义的方法时,__call()方法会自动被调用。

示例如下:

<?php
class Person
{                             
    function say()
    {
           echo "Hello, world!<br>";
    }     
    function __call($funName, $arguments)
    {
          echo "The function you called:" . $funName . "(parameter:" ;  // 输出不存在的方法的名称
          print_r($arguments); // 输出不存在的方法的参数列表
          echo ")does not exist!!<br>\n";                   
    }                                         
}
$Person = new Person();           
$Person->run("teacher"); // 如果对象内不存在的方法被调用,则 __call() 方法会被自动调用
$Person->eat("John", "apple");             
$Person->say();

输出结果如下:

The function you called: run (parameter: Array([0] => teacher)) does not exist!
The function you called: eat (parameter: Array([0] => John[1] => apple)) does not exist!
Hello world!

评 论

View in WeChat

Others Discussion

  • PHP没你想的那么差
    Posted on 2021-12-17 15:40
  • 2016年云计算热词
    Posted on 2019-06-12 17:53
  • 快速了解Kafka
    Posted on 2021-03-25 14:20
  • 通过信鸽来解释HTTPS
    Posted on 2018-10-22 13:56
  • PHP7不兼容性
    Posted on 2018-03-07 15:59
  • 分布式架构之「 数据分布」
    Posted on 2019-11-14 10:00
  • PHP扩展ImageMagick安装
    Posted on 2022-11-11 11:16
  • Redis各种数据类型的使用场景举例分析【三】
    Posted on 2018-11-22 17:00