5

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

3 Answers 3

3

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, ...) {.

Sign up to request clarification or add additional context in comments.

Comments

2

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).

Comments

1

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);
  });
..

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.