Anonymous function returns class properties? PHP
我在读一个WordPress教程,其中作者使用了类似的东西(我简化了它):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
该函数应该从wp查询的对象中删除
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
号
我还在学习匿名函数,我想知道它是如何/为什么这样做的?如果从对象调用匿名函数,它是否创建该对象的实例或其他对象?
另外,如果我使用了不正确的术语,很抱歉。没有匿名函数、闭包和lambda函数。
不是一个新的实例,它引用了自php 5.4以来创建它的同一个对象。因此,闭包本身可以对该类调用属性或方法,就像在该类中一样。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 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" |