This article will introduce you to the PHP Closure class and how to use Closure to create anonymous functions. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Recommended learning: "PHP Video Tutorial"
Use For classes that represent anonymous functions.
Anonymous functions (introduced in PHP 5.3) produce objects of this type. In the past, this class was considered an implementation detail, but now it can be relied upon to do something. As of PHP 5.4,
this class comes with methods that allow more control over the anonymous function after it has been created.
This class cannot be instantiated. There are two main methods in it, both of which are used to copy closures, one static and one dynamic. These two difficult-to-understand methods are explained in detail below.
public static Closure Closure::bind ( Closure $closure , object $newthis [, mixed $newscope = 'static' ] ) 参数说明: closure 需要绑定的匿名函数。 newthis 需要绑定到匿名函数的对象,或者 NULL 创建未绑定的闭包。 newscope 想要绑定给闭包的类作用域,或者 'static' 表示不改变。如果传入一个对象,则使用这个对象的类型名。 类作用域用来决定在闭包中 $this 对象的 私有、保护方法 的可见性。 The class scope to which associate the closure is to be associated, or 'static' to keep the current one. If an object is given, the type of the object will be used instead. This determines the visibility of protected and private methods of the bound object.
The above is the definition of this method. The first parameter is easy to understand, it is a closure function; the second parameter is not It’s easy to understand. If the closure to be copied contains $this
, this object represents this $this
. The modification of this object in the closure function ends at the end of the call. It will remain consistent in the future, for example, if an attribute is modified; the third parameter is not easy to understand, and the official instructions are also unclear.
With default parameters, call $this-> ;
When accessing the attribute functions in object $newthis
, there will be restrictions. You can only access the functions with public
attributes. If you want to access protected/private
Attribute,
must be set to the corresponding class name/class instance, and the protected/private attribute function of that class must be accessed just like in the class.
<?php class T { private function show() { echo "我是T里面的私有函数:show\n"; } protected function who() { echo "我是T里面的保护函数:who\n"; } public function name() { echo "我是T里面的公共函数:name\n"; } } $test = new T(); $func = Closure::bind(function(){ $this->who(); $this->name(); $this->show(); }, $test); $func();
The above code will report an errorFatal error: Uncaught Error: Call to protected method T::who() from context 'Closure'
. Add the third parameter of bind to t::class
or new T()
, and each result will be output normally.
我是T里面的保护函数:who 我是T里面的公共函数:name 我是T里面的私有函数:show
Of course, closures can also pass parameters
$test = new StdClass(); var_dump($test); $func = Closure::bind(function($obj){ $obj->name = "燕睿涛"; }, null); $func($test); var_dump($test);
The above program is the same as the anonymous function and has no dependencies on any objects. The above program will output:
object(stdClass)#1 (0) { } object(stdClass)#1 (1) { ["name"]=> string(9) "燕睿涛" }
There is also a special example that needs to be explained
<?php class T { private function show() { echo "我是T里面的私有函数:show\n"; } protected function who() { echo "我是T里面的保护函数:who\n"; } public function name() { echo "我是T里面的公共函数:name\n"; } } $func = Closure::bind(function ($obj) { $obj->show(); }, null); $test = new T(); $func($test);
What will be output in the above situation? Yes, an error will be reported, indicating that the private attribute cannot be accessedshow
. At this time, add the third Just one parameter is enough. After seeing that the third parameter not only affects the scope of $this
,
can also affect the scope of the parameter.
bindTo
has similar functions to bind
, here is just another form, both areCopy the current closure object and bind the specified $this object and class scope.
, the first parameter is less than bind
,
the last two are the same, of course there is another difference that bindTo
is not a static method, it exists only because of a closure a property method.
<?php class T { private function show() { echo "我是T里面的私有函数:show\n"; } protected function who() { echo "我是T里面的保护函数:who\n"; } public function name() { echo "我是T里面的公共函数:name\n"; } } $func = function () { $this->show(); $this->who(); $this->name(); }; $funcNew = $func->bindTo(new T(), T::class); $funcNew();
The output of the above function is similar to bind
我是T里面的私有函数:show 我是T里面的保护函数:who 我是T里面的公共函数:name
This function was encountered when looking at the automatic loading source code generated by composer. It is used in composer quite specially. The following is an interception of part of the code in composer
// 文件autoload_real.php call_user_func(\Composer\Autoload\ComposerStaticInit898ad46cb49e20577400c63254121bac::getInitializer($loader)); // 文件autoload_static.php public static function getInitializer(ClassLoader $loader) { return \Closure::bind(function () use ($loader) { $loader->prefixLengthsPsr4 = ComposerStaticInit25885cdf386fdaafc0bce14bb5a7d06e::$prefixLengthsPsr4; $loader->prefixDirsPsr4 = ComposerStaticInit25885cdf386fdaafc0bce14bb5a7d06e::$prefixDirsPsr4; $loader->prefixesPsr0 = ComposerStaticInit25885cdf386fdaafc0bce14bb5a7d06e::$prefixesPsr0; $loader->classMap = ComposerStaticInit25885cdf386fdaafc0bce14bb5a7d06e::$classMap; }, null, ClassLoader::class); }
The above code is rather strange. , in call_user_func
, the first impression is that the wrong parameters are passed, but this is not the case. A function is called here, and this function will return a Closure
object,
which is an anonymous Function, the final parameter passed in is still a callable
type. Look at the returned closure again. use
is used in it. This is the bridge connecting the closure and external variables.
As for why ordinary parameters can be passed here, it is because in php5, the object formal parameters and actual parameters point to the same object, and modifications to the object in the function will be reflected outside the object.
So, it’s okay to do the above, there is another way too
call_user_func(\Composer\Autoload\ComposerStaticInit898ad46cb49e20577400c63254121bac::getInitializer(), $loader); public static function getInitializer() { return \Closure::bind(function ($loader) { $loader->prefixLengthsPsr4 = ComposerStaticInit25885cdf386fdaafc0bce14bb5a7d06e::$prefixLengthsPsr4; $loader->prefixDirsPsr4 = ComposerStaticInit25885cdf386fdaafc0bce14bb5a7d06e::$prefixDirsPsr4; $loader->prefixesPsr0 = ComposerStaticInit25885cdf386fdaafc0bce14bb5a7d06e::$prefixesPsr0; $loader->classMap = ComposerStaticInit25885cdf386fdaafc0bce14bb5a7d06e::$classMap; }, null, ClassLoader::class); }
I haven’t written a blog for a long time Sometimes I am too agitated and can’t calm down, and sometimes I can’t find what I want to write. You still have to calm down, do everything well, don't be agitated when things happen, keep an open mind, and handle everything calmly.
At the end of writing, I suddenly remembered that when I was in high school, it happened to be the time of the 5.12 Wenchuan earthquake. We were in Xi'an. After the earthquake, there were still aftershocks. As soon as there were even slight aftershocks, everyone panicked and swarmed. Rushing down, if I remember correctly, we were on the 5th floor,
until one time our physics teacher came to class. This teacher was older and was a special teacher in the city (well, that should be right), and happened to encounter an aftershock. , everyone was going crazy and ready to run out again. At this time, the teacher said something that I will never forget. Life is in my bones. There is no need to squeeze in such aftershocks. No matter how hard your life is, it will be fine.
, indeed, accidents may be more likely to occur if such small aftershocks are squeezed. Although this sentence brings a little negativity, it is more of a calm state of mind, a big heart, and a calm and decisive reflection. This is what I want to learn.
What should appear will always appear, and what should not appear will never appear. Blindly aiming too high and pursuing too far a goal can easily lead to anxiety. Of course, do not belittle yourself. In a word: be calm, be magnified, and be considerate. Don't worry about gains and losses, do everything well in a down-to-earth manner, the harder you work, the luckier you will be, the luckier you will be, the harder you work.
For more programming related knowledge, please visit:
Programming Video
The above is the detailed content of A brief discussion of the PHP Closure class and its usage. For more information, please follow other related articles on the PHP Chinese website!