Modify a globally scoped variable inside of an anonymous function

✔ Recommended Answer

Yes, use a closure:

functionName($someArgument, function() use(&$variable) {  $variable = "something";});

Note that in order for you to be able to modify $variable and retrieve the modified value outside of the scope of the anonymous function, it must be referenced in the closure using &.


Answered By: nickb

Method #2

To modify a globally scoped variable inside an anonymous function, you can use the window object in a web browser or the global object in Node.js.

For example, if you have a global variable called myVar and you want to modify it inside an anonymous function, you can do the following:

// Define the global variable let myVar = 0; // Call the anonymous function and modify the global variable (() => { window.myVar = 1; })(); console.log(myVar); // Output: 1

In this example, the anonymous function is called immediately and modifies the myVar variable by assigning the value 1 to window.myVar. Since window is the global object in a web browser, this modifies the global myVar variable.

Note that modifying global variables can be a bad programming practice as it can lead to unintended side effects and make code difficult to maintain. It's generally better to pass variables as arguments to functions or encapsulate them in a module or class.


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