0

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.

1
  • It's just giving you the value of $this which is an instance of your WPObject class Commented Oct 24, 2013 at 0:31

1 Answer 1

1

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"
Sign up to request clarification or add additional context in comments.

1 Comment

thank you for the walkthrough. i was just having a hard time wrapping my head around it and that helped me a lot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.