Understanding the __invoke() Magic Method in PHP

This article explains PHP's __invoke() magic method, showing how defining __invoke() allows an object to be called like a function, demonstrates usage with a Person class example, and notes version requirements and error behavior when misused.

php Courses
php Courses
php Courses
Understanding the __invoke() Magic Method in PHP
__invoke()

is the magic method that PHP automatically calls when an object is invoked as a function.

Purpose:

When you attempt to call an object like a function, the __invoke() method is automatically executed.

Note:

This feature is available only in PHP version 5.3.0 and later.

Code Example:

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

Result:

这可是一个对象哦

If you insist on treating the object as a function without defining __invoke(), PHP will produce a fatal error such as:

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

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backend DevelopmentprogrammingPHPMagic MethodObject Invocation
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.