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
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.
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.
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.
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).
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, ...) {
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With