Home  >  Article  >  Backend Development  >  Detailed explanation of __invoke() method in PHP

Detailed explanation of __invoke() method in PHP

藏色散人
藏色散人Original
2019-07-25 14:20:0119087browse

__invoke(), the response method when calling an object by calling a function

Function:

When trying to call a function When calling an object, the __invoke() method is automatically called.

Note:

This feature is only valid in PHP 5.3.0 and above.

Go directly to the code:

<?php
class Person
{
    public $sex;
    public $name;
    public $age;
    public function __construct($name="",  $age=25, $sex=&#39;男&#39;)
    {
        $this->name = $name;
        $this->age  = $age;
        $this->sex  = $sex;
    }
    public function __invoke() {
        echo &#39;这可是一个对象哦&#39;;
    }
}
$person = new Person(&#39;小明&#39;); // 初始赋值
$person();

View the running results:

这可是一个对象哦

Of course, if you insist on using the object as a function method, you will get the following results:

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

The above is the detailed content of Detailed explanation of __invoke() method in PHP. For more information, please follow other related articles on the PHP Chinese website!

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