How to pass multiple variables from global scope into callback scope?
✔ Recommended Answer
$filter_name
is not available in anonymous function, so you need to use
it, same as you do with $search_text
:
$expected88 = array_filter($array, function($el) use ($search_text, $filter_name) { return ( stripos($el[$filter_name], $search_text) !== false );});
Source: stackoverflow.com
Answered By: u_mulder
In order to pass multiple variables from global scope to the callback scope, there are a few different approaches you can take. Here are three common methods:
- Pass the variables as arguments to the callback function: You can define the callback function to take parameters for each of the variables you want to pass in from the global scope. Then, when you call the function, you can pass in the variables as arguments. For example:
javascriptvar globalVariable1 = 'Hello';
var globalVariable2 = 'world';
function myCallbackFunc(param1, param2) {
console.log(param1 + ' ' + param2);
}
myCallbackFunc(globalVariable1, globalVariable2); // Output: "Hello world"
- Use closures: You can define the callback function within a closure that has access to the global variables. This allows the callback function to access the variables even though they are not directly passed in as arguments. For example:
javascriptvar globalVariable1 = 'Hello';
var globalVariable2 = 'world';
function myClosure() {
var localVariable = 'from closure';
function myCallbackFunc() {
console.log(globalVariable1 + ' ' + globalVariable2 + ' ' + localVariable);
}
return myCallbackFunc;
}
var callbackFunc = myClosure();
callbackFunc(); // Output: "Hello world from closure"
- Use an object or array to hold the variables: You can define an object or array in the global scope that holds the variables you want to pass to the callback function. Then, you can pass a reference to the object or array to the callback function, which can access the variables through the reference. For example:
javascriptvar globalVariables = {
variable1: 'Hello',
variable2: 'world'
};
function myCallbackFunc(variables) {
console.log(variables.variable1 + ' ' + variables.variable2);
}
myCallbackFunc(globalVariables); // Output: "Hello world"
Each of these methods has its own advantages and disadvantages, depending on the specific use case.
Comments
Post a Comment