PHP魔术方法__invoke()

2018-09-17 23:00 By "Powerless" 2837 0 1

注意:该功能只在PHP 5.3.0以及以上版本上有效。

示例代码如下:

<?php
class Person
{
    public $sex;
    public $name;
    public $age;
    public function __construct($name="",  $age=25, $sex='Male')
    {
        $this->name = $name;
        $this->age  = $age;
        $this->sex  = $sex;
    }
    public function __invoke() {
        echo 'This is an object';
    }
}
$person = new Person('John'); // 赋初始值
$person();

输出结果如下:

This is an object

如果在未定义__invoke()方法的情况下将对象作为函数使用,就会得到以下的结果:

Fatal error: Function name must be a string in D:\phpStudy\WWW\test\index.php on line 18

评 论

View in WeChat

Others Discussion

  • PHP练习-无重复字符的最长子串
    Posted on 2020-09-17 18:03
  • PHP练习-移动数组内的0到最后并保持其他元素顺序不变
    Posted on 2020-08-14 20:32
  • PHP设计模式 - 委托模式
    Posted on 2019-04-25 16:15
  • HTTP头中隐藏PHP版本号
    Posted on 2021-01-11 16:38
  • Composer 异常 [ErrorException]
    Posted on 2019-11-25 17:55
  • PHP8.1 性能基准测试
    Posted on 2022-10-08 17:40
  • 必学十大经典排序算法,看这篇就够了
    Posted on 2019-11-18 16:30
  • Linux工具 - NM目标文件格式分析
    Posted on 2019-04-24 10:29