PHP Closure accessing non Global Variable inside functions

I am trying to prevent some of my variables from being accessed from other PHP files but am having trouble accessing the variables defined outside of a function without creating a global variable. I need the variables to be reused in several functions inside the scope but not outside of the file. Any ideas?

(function() {
$myVariable = 'string';

function customFunction() {
 // how do I access $myVariable without declaring it as a global?
}

})();

Pass them as a parameter when you call the function.

customFunction($myVariable)

Or close over it using the use keyword:

(function() {
$myVariable = 'string';

function customFunction() use ($myVariable) {
 // now you can access $myVariable
}

})();

I’m aware of passing arguments but for this particular configuration that won’t work.

I’ve actually tried this but I keep getting an error unexpected ‘use’;

The function is triggered by an action, not sure if that changes anything. For whatever reason, just not able to get that to work.

(function() {
$myVariable = 'string';


function customFunction() use ($myVariable) {
// Getting error unexpected 'use'
}

add_action('add_customFunction', 'customFunction');

})();

What PHP version are you on? Sounds like it might be an ancient one…

use is only valid on anonymous functions.

You can always Pass By Reference a function parameter by sticking & in front of it tho…

Duh, of course :man_facepalming: