匿名函数返回类属性? PHP

时间:2013-10-24 00:20:27

标签: php anonymous-function

我正在阅读一个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;
           }
       ];
    }
}

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

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

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

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

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

1 个答案:

答案 0 :(得分:1)

不是 new 实例,它引用了自从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"