What is the use of php invoke method?

藏色散人
Release: 2023-03-04 20:20:01
Original
3797 people have browsed it

php invoke method is a new magic method in PHP5.3. This method can directly call the object after creating the instance, that is, use the object through a function, and the invoke method can also take parameters.

What is the use of php invoke method?

Recommended: "PHP Video Tutorial"

PHP5.3 has a new feature called __invoke Magic method so that the object can be called directly after the instance is created.

is to use objects in a functional way. For example, I now have a class A. If I want to prevent others from directly outputting objects, then I can do this:

class A {
    public function __invoke()
    {
        return '不允许这样使用';
    }

}

$a = new A();

echo $a();
Copy after login

Then it will output "No Such use is permitted."

__invoke() method can also be used with parameters:

class A {
    public function __invoke($a,$b)
    {
        return "传入的参数a:{$a},b:{$b}";
    }

}

$a = new A();

echo $a(1,2);
Copy after login

Then you can output:


This method You can also call it directly through the class.

Of course, you can also call other methods of this class, but the permission modifier cannot be set to private, and protected;

The above is the detailed content of What is the use of php invoke method?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!