How to specify this for anonymous functions in PHP

autoload
Release: 2023-03-09 10:34:02
forward
2132 people have browsed it

How to specify this for anonymous functions in PHP

Regarding closure anonymous functions, a very typical problem inJSis to bind it to athisscope. In fact, this problem also exists inPHP, such as the following code:

$func = function($say){ echo $this->name, ':', $say, PHP_EOL; }; $func('good'); // Fatal error: Uncaught Error: Using $this when not in object context
Copy after login

In this anonymous function, we use$this->nameTo get the$nameattribute under the current scope, but who is this$this? We have not defined it, so an error will be reported directly here. The error message is:$thisis used but there is no object context, that is, the scope of the $this reference is not specified.

1.bindTo() method binding $this

$func = $func->bindTo($lily, 'Lily'); // $func = $func->bindTo($lily, Lily::class); // $func = $func->bindTo($lily, $lily); $func1('cool');
Copy after login

This time you can output normally.bindTo()The method is to copy a current closure object and then bind it to the$thisscope and class scope.

  • The $lily parameter is aobject $newthisparameter, which is to specify$thisfor this copied anonymous function.

  • 'Lily' binds a new class scope, which represents a type and determines which private and protected methods can be called in this anonymous function

If this parameter is not given, then we cannot access the$nameattribute of thisprivate:

$func1 = $func->bindTo($lily); $func1('cool2'); // Fatal error: Uncaught Error: Cannot access private property Lily::$name
Copy after login

2.call() method binding $this

$func->call($lily, 'well'); // Lily:well
Copy after login

Recommended:2021 PHP interview questions summary (collection)》《php video tutorial

The above is the detailed content of How to specify this for anonymous functions in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:imooc.com
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
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!