Anonymous function returns class properties? PHP

I was reading a WordPress tutorial in which the author used something like this (I simplified it):

class WPObject {
    public $ID;
    public $title;
    public $content;
    public $status;

    public function __construct($wp_post) {
       $modifiers = [ 
           'key' => function($k, $v) { 
               return (substr($k, 0, 5) === "post_") ? substr($k, 5) : $k;
           }
       ];
    }
}

The function is supposed to remove the post_ prefix from the wp queried object. The question I have is regarding the function I posted above. That anonymous function seems to return an object with with the properties. When I did a print_r on it I get...

Array
(
    [key] => Closure Object
        (
            [this] => WPObject Object
                (
                    [ID] => 
                    [title] => 
                    [content] => 
                    [status] => 
                )

            [parameter] => Array
                (
                    [$k] => 
                    [$v] => 
                )
        )
)

I'm still learning about anonymous functions and was wondering how/why it does this? If you call an anonymous function from an object, does it create an instance of that object or something?

Also, sorry if I'm using incorrect terminology. Don't have anonymous functions, closures, lambda functions straightened out yet.


Not a new instance, it has a reference to the same object in which it is created since PHP 5.4 I believe. So the closure itself can call properties or methods on that class as if being in that class.

class foo {
       public $bar = 'something';
       function getClosure(){
          return function(){
             var_dump($this->bar);
          };
       }
    }

$object = new foo();
$closure = $object->getClosure();
//let's inspect the object
var_dump($object);
//class foo#1 (1) {
//  public $bar =>
//  string(9) "something"
//}

//let's see what ->bar is
$closure();
//string(9) "something"

//let's change it to something else
$object->bar = 'somethingElse';

//closure clearly has the same object:
$closure();
//string(13) "somethingElse"

unset($object);
//no such object/variables anymore
var_dump($object);
//NULL (with a notice)

//but closure stills knows it as it has a reference
$closure();
//string(13) "somethingElse"
链接地址: http://www.djcxy.com/p/51696.html

上一篇: 什么时候应该在ECMAScript 6中使用Arrow函数?

下一篇: 匿名函数返回类属性? PHP