Home  >  Article  >  Backend Development  >  How to specify this for anonymous functions in PHP

How to specify this for anonymous functions in PHP

autoload
autoloadforward
2021-04-06 16:45:192203browse

How to specify this for anonymous functions in PHP

Regarding closure anonymous functions, a very typical problem in JS is to bind it to a this scope. In fact, this problem also exists in PHP, 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

In this anonymous function, we use $this->name To get the $name attribute 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: $this is 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');

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

  • The $lily parameter is a object $newthis parameter, which is to specify $this for 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 $name attribute of this private:

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

2.call() method binding $this

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

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!

Statement:
This article is reproduced at:imooc.com. If there is any infringement, please contact admin@php.cn delete
Previous article:How to read php error logNext article:How to read php error log