1

I have the following code:

class Demo
{
    private $data = array();

    public function foo($key, $value)
    {
        $this->data[$key] = function ($c) use ($value) {
            return $c + $value;
        });
    }
}

As you can see the foo method sets the $key using an anonymous function. And it uses the use($value) syntax.

How to achieve this in a PHP extension?

Oldskool
  • 34,211
  • 7
  • 53
  • 66
eaglewu
  • 458
  • 5
  • 12
  • Improved grammar and layout – Oldskool Jun 23 '15 at 08:45
  • What do you want to achieve in your extension? – hek2mgl Jun 23 '15 at 09:02
  • Just want to declare an anonymous function for a variable. @hek2mgl – eaglewu Jun 24 '15 at 07:43
  • Meaning your extension exposes a function which will return an anonymous function to the PHP userland? – hek2mgl Jun 24 '15 at 08:52
  • Yes right. @hek2mgl What should i do in PHP extension. – eaglewu Jun 24 '15 at 13:37
  • I'm not sure if this is possible at all.. Let me check that at home. Will give you a feedback.. – hek2mgl Jun 24 '15 at 13:54
  • @0X07DE I don't think that this possible unless you create the opcode (that what usually the PHP parser creates) of the function in C code and fake the function starting line, source filename etc. (Mind reflection). Why would you do that in an extension? You can simply use the code as above in your question, isn't it? – hek2mgl Jun 24 '15 at 22:59
  • @hek2mgl Thanks for the result "that what usually the PHP parser creates". Anyway thank you very much for follow-up this answer : ) – eaglewu Jun 25 '15 at 04:31
  • You will need to declare a normal function as a callback (if you start the name with a NUL byte, it will not show up in function lists). Then either return an ordinary function callback or create a closure from it using zend_create_closure, if you have a strict requirement of returning a Closure instance. – NikiC Jul 03 '15 at 14:01

0 Answers0