Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot access variable within function as variable

Tags:

php

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
like image 517
Adam W Avatar asked May 20 '15 09:05

Adam W


People also ask

Can you access a variable inside a function?

You can access such variables inside and outside of a function, as they have global scope. The variable x in the code above was declared outside a function: x = 10 . Using the showX() function, we were still able to access x because it was declared in a global scope.

How do you access a variable inside a function in Python?

The variables that are defined inside the methods can be accessed within that method only by simply using the variable name. Example – var_name. If you want to use that variable outside the method or class, you have to declared that variable as a global.

How do you find the variable inside a function?

Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.

Can a function access global variable?

Functions can access global variables and modify them. Modifying global variables in a function is considered poor programming practice. It is better to send a variable in as a parameter (or have it be returned in the 'return' statement).


1 Answers

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

like image 83
TiMESPLiNTER Avatar answered Sep 30 '22 05:09

TiMESPLiNTER