Home >Backend Development >PHP Problem >What is the use of php invoke method?

What is the use of php invoke method?

藏色散人
藏色散人Original
2020-08-20 10:20:523847browse

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();

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);

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!

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