0

我正在阅读一个 WordPress 教程,其中作者使用了这样的东西(我简化了它):

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;
           }
       ];
    }
}

该函数应该post_从 wp 查询对象中删除前缀。我的问题是关于我上面发布的功能。该匿名函数似乎返回具有属性的对象。当我对其进行 print_r 时,我得到...

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

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

我仍在学习匿名函数,想知道它是如何/为什么这样做的?如果您从对象调用匿名函数,它会创建该对象的实例还是什么?

另外,对不起,如果我使用了不正确的术语。还没有理顺匿名函数、闭包、lambda 函数。

4

1 回答 1

1

不是一个实例,它引用了自 PHP 5.4 以来创建它的同一对象,我相信。因此闭包本身可以调用该类的属性或方法,就好像在该类中一样。

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"
于 2013-10-24T00:34:58.297 回答