JavaEar 专注于收集分享传播有价值的技术资料

Php, what to use instead of create_function()?

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个回答

    最佳答案
  1. 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