Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php closures: why the 'static' in the anonymous function declaration when binding to static class?

Tags:

closures

php

bind

The example in the php documentation on Closure::bind include static on the anonymous function declaration. why? I can't find the difference if it is removed.

with:

class A {     private static $sfoo = 1; } $cl1 = static function() { // notice the "static"     return self::$sfoo; }; $bcl1 = Closure::bind($cl1, null, 'A'); echo $bcl1(); // output: 1 

without:

class A {     private static $sfoo = 1; } $cl1 = function() {     return self::$sfoo; }; $bcl1 = Closure::bind($cl1, null, 'A'); echo $bcl1(); // output: 1 
like image 962
learning php Avatar asked Nov 11 '13 05:11

learning php


People also ask

What is static closure in PHP?

Closure are functions that may be stored in a variable : functions may have their name stored in a variable, though. Closure also have the ability to aggregate variables from the context of their creation, for future use. As such, $this is available in a closure that is created inside an object.

Is closure and anonymous function same?

Anonymous functions, also known as closures , allow the creation of functions which have no specified name. They are most useful as the value of callable parameters, but they have many other uses. Anonymous functions are implemented using the Closure class.

Why do we use static in PHP?

The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.

What is a closure in PHP and why does it use the use identifier?

A closure is a separate namespace, normally, you can not access variables defined outside of this namespace. There comes the use keyword: use allows you to access (use) the succeeding variables inside the closure. use is early binding. That means the variable values are COPIED upon DEFINING the closure.


1 Answers

found the difference: you can't bind static closures to object, only change the object scope.

class foo { }  $cl = static function() { };  Closure::bind($cl, new foo); // PHP Warning:  Cannot bind an instance to a static closure Closure::bind($cl, null, 'foo') // you can change the closure scope 
like image 145
learning php Avatar answered Sep 21 '22 09:09

learning php