Adam W
Adam W

Reputation: 337

Cannot access variable within function as variable

I cannot access a variable within a function as a variable:

public function fetchWhere($params) {
  $resultSet = $this->select(function(Select $select) {
    $select->where($params);
  });
..

I get the error:

Undefined variable: params

Upvotes: 5

Views: 181

Answers (3)

TiMESPLiNTER
TiMESPLiNTER

Reputation: 5889

You need the use construct then to make the variable available/visible inside the function:

public function fetchWhere($params) {
    $resultSet = $this->select(function(Select $select) use($params) {
        $select->where($params);
    });
}

You can pass even more than just one variable with this. Just separate other variables with a comma , like ... use($param1, $param2, ...) {.

Upvotes: 3

Thibault Henry
Thibault Henry

Reputation: 841

use "use", that let you use a variable as a global in the scope :

public function fetchWhere($params) {
  $resultSet = $this->select(function(Select $select) use($params) {
    $select->where($params);
  });
..

Upvotes: 1

Sougata Bose
Sougata Bose

Reputation: 31749

Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct. It is because of variable scope. Try with -

$resultSet = $this->select(function(Select $select) use($params) {
   $select->where($params);
});

Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from).

Upvotes: 2

Related Questions