Detailed explanation of __invoke() method in PHP

藏色散人
Release: 2023-04-07 06:44:02
Original
19098 people have browsed it

__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();
Copy after login

View the running results:

这可是一个对象哦
Copy after login

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
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template