2

I know the differences between Lambda and Closures. I dont want to use Closure since it gets its environment, and var_dump()-ing it would result a tons of output. Using lambda with create_function() looked a good idea, but its getting deprecated. Then what to use to create functions that not aware in their enviromnent?

1
  • 2
    PHP anonymous functions do not capture their environment. The documentation says: "Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct." Commented Apr 29, 2017 at 11:08

1 Answer 1

2

Use static closure:

As of PHP 5.4, anonymous functions may be declared statically. This prevents them from having the current class automatically bound to them. Objects may also not be bound to them at runtime.

<?php

class Foo
{
    function __construct()
    {
        $func = static function() {
            var_dump($this);
        };
        $func();
    }
};
new Foo();

?>

yields

Notice: Undefined variable: this in %s on line %d
NULL
Sign up to request clarification or add additional context in comments.

Comments

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.