Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, The Closure class

I am trying to understand about the closure class, at the manual there is, All at the manual Link,

Closure::__construct - Constructor that disallows instantiation. If i understand it right the only instance of this class is for anonymous function variable assignment.

But i did not understand few lines:

Closure::bind — Duplicates a closure with a specific bound object and class scope.

Closure::bindTo — Duplicates the closure with a new bound object and class scope.

And the last at the manual i did not understand this sentence:

Besides the methods listed here, this class also has an __invoke method. This is for consistency with other classes that implement calling magic, as this method is not used for calling the function.

If can some one please try to explain thoes lines to me i will be very thankful, Have a nice day.

like image 935
Aviel Fedida Avatar asked Jul 21 '12 12:07

Aviel Fedida


2 Answers

I think the difference between bind and bindTo is just in the way they're called:

$cl->bindTo($obj)

is equivalent to

Closure::bind($cl, $obj)

Regarding the __invoke meethod, it's saying that the method exists, but it's not actually used. When you use the closure as a function, an internal (probably more efficient) mechanism is used that bypasses the method. But the method is there for compatibility with other classes that are callable, and you could call it manually if you wanted to.

like image 26
Barmar Avatar answered Sep 21 '22 23:09

Barmar


It is referring to the calling magic.

As my understanding, for any class that contains the method __invoke which its instances can be called as if it is a function. The Closure::__invoke acts like that.

i.e. when $foo is of class Closure (anonymous function), calling $foo($bar) will call $foo->__invoke(bar) (although the __invoke member is not meant to be called directly, this is just to show how it works).

When you define anonymous functions, you do this:

$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};

Now, $greet is of class Closure. and $greet->__invoke is sort of equal to function($name){ printf("Hello %s\r\n", $name); }

And remember, Closure::__invoke is a Magic Method.

like image 127
Alvin Wong Avatar answered Sep 23 '22 23:09

Alvin Wong