Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: limit the scope of functions to within current file only

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.

like image 816
roverred Avatar asked Aug 06 '13 23:08

roverred


People also ask

Does PHP have function scope?

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.

How can use global variable inside function in PHP?

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.

What is local variable in PHP?

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.


1 Answers

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
like image 113
Inglis Baderson Avatar answered Sep 19 '22 00:09

Inglis Baderson