PHP魔术方法__invoke()

2018-09-17 23:00 By "Powerless" 2833 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

  • 分布式架构之「 数据分布」
    Posted on 2019-11-14 10:00
  • PHP扩展ImageMagick安装
    Posted on 2022-11-11 11:16
  • PHP7不兼容性
    Posted on 2018-03-07 15:59
  • Redis各种数据类型的使用场景举例分析【三】
    Posted on 2018-11-22 17:00
  • 投票通过,PHP 8 确认引入 Union Types 2.0
    Posted on 2019-11-18 22:22
  • PHP设计模式 - 委托模式
    Posted on 2019-04-25 16:15
  • BASE原则
    Posted on 2020-12-17 16:42
  • 程序员年中考试题-段子版
    Posted on 2021-06-23 15:57