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

Method #2

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:

  1. 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:
javascript
var globalVariable1 = 'Hello'; var globalVariable2 = 'world'; function myCallbackFunc(param1, param2) { console.log(param1 + ' ' + param2); } myCallbackFunc(globalVariable1, globalVariable2); // Output: "Hello world"
  1. 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:
javascript
var 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"
  1. 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:
javascript
var 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

Most Popular

Remove Unicode Zero Width Space PHP

PhpStorm, return value is expected to be 'A', 'object' returned

Laravel file upload returns forbidden 403, file permission is 700 not 755