roverred
roverred

Reputation: 1921

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.

Upvotes: 8

Views: 2091

Answers (1)

Inglis Baderson
Inglis Baderson

Reputation: 799

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

Upvotes: 2

Related Questions