Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP closure scope problem

Apparently $pid is out of scope here. Shouldn't it be "closed" in with the function? I'm fairly sure that is how closures work in javascript for example.

According to some articles php closures are broken, so I cannot access this?

So how can $pid be accessed from this closure function?

class MyClass {
  static function getHdvdsCol($pid) {
    $col = new PointColumn();
    $col->key = $pid;
    $col->parser = function($row) {
        print $pid; // Undefined variable: pid
    };
    return $col;
  }
}

$func = MyClass::getHdvdsCol(45);
call_user_func($func, $row);

Edit I have gotten around it with use: $col->parser = function($row) use($pid). However I feel this is ugly.

like image 380
Keyo Avatar asked Jul 01 '11 03:07

Keyo


People also ask

Is closure a scope function?

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.

What is a PHP closure?

Basically a closure in PHP is a function that can be created without a specified name - an anonymous function. Here's a closure function created as the second parameter of array_walk() . By specifying the $v parameter as a reference one can modify each value in the original array through the closure function.

Is a closure callable?

In PHP, a closure is a callable class, to which you've bound your parameters manually.

Is closure an anonymous function?

Anonymous functions, also known as closures , allow the creation of functions which have no specified name. They are most useful as the value of callable parameters, but they have many other uses. Anonymous functions are implemented using the Closure class.


1 Answers

You need to specify which variables should be closed in this way:

function($row) use ($pid) { ... }
like image 50
zerkms Avatar answered Sep 20 '22 07:09

zerkms