Search code examples
phparray-map

array_map not allow to pass object in use()


I am trying this:

array_map(function($data) use ($this->id) {
   //code
}, $arr);

I'm getting an error that I can not pass an object to use().

What am I doing wrong?

Thanks


Solution

  • You don't need to pass anything from $this to the closure. $this is available in closures by default. Example:

    class A {
        private $id = 500;
    
        function B() {
            $arr = [1, 2, 3];
            array_map(
                function($data) {
                    echo "I'm data $data with id {$this->id}\n";
                },
                $arr
            );
        }
    }
    
    $a = new A();
    $a->B();
    

    This code will print

    I'm data 1 with id 500
    I'm data 2 with id 500
    I'm data 3 with id 500
    

    Or if you want to pass anything to the use construct instead of using $this directly, just assign your value to a variable and then pass this simple variable to use. You can not list expressions in use.