【问题标题】:Anonymous function returns class properties? PHP匿名函数返回类属性? PHP
【发布时间】:2013-10-24 00:20:26
【问题描述】:

我正在阅读一个 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 函数。

【问题讨论】:

  • 它只是给你$this 的值,它是你的WPObject 类的一个实例

标签: php anonymous-function


【解决方案1】:

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

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"

【讨论】:

  • 感谢您的演练。我只是很难理解它,这对我有很大帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-29
  • 2015-12-07
  • 2013-03-29
  • 2019-05-04
  • 1970-01-01
  • 2012-04-15
  • 2014-09-14
相关资源
最近更新 更多