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.
__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 18Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
