Is there any way to limit the scope of non-class functions in a php file and making them the only accessible within the php file it is located in? Like how C can achieve this using static keyword with functions. In php static seems to be for classes only. I want to hide helper functions that should only be accessed by functions within the file. Thanks.
Very simple: PHP has function scope. That's the only kind of scope separator that exists in PHP. Variables inside a function are only available inside that function. Variables outside of functions are available anywhere outside of functions, but not inside any function.
Accessing global variable inside function: The ways to access the global variable inside functions are: Using global keyword. Using array GLOBALS[var_name]: It stores all global variables in an array called $GLOBALS[var_name]. Var_name is the name of the variable.
Local variableThe variables that are declared within a function are called local variables for that function. These local variables have their scope only in that particular function in which they are declared. This means that these variables cannot be accessed outside the function, as they have local scope.
The closest solution I can figure out is this:
<?php
call_user_func( function() {
//functions you don't want to expose
$sfunc = function() {
echo 'sfunc' . PHP_EOL;
};
//functions you want to expose
global $func;
$func = function() use ($sfunc) {
$sfunc();
echo 'func' . PHP_EOL;
};
} );
$func();
?>
But you have to call the functions like $func()
instead of func()
. The problem is that it breaks when you re-assign $func
to other value.
$func = 'some other value';
$func(); //fails
Of course you can create wrapper functions:
function func() {
$func();
}
In this way you can call it like func()
, but the re-assigning problem still exists:
$func = 'some other value';
func(); //fails
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