tags:

views:

41

answers:

3

I've been using the following snippet to include multiple files:

foreach(glob(APP_PATH."libs/*.php") as $path)
{
 include $path;
}

The thing is, I don't want to have the $path variable available inside the included files.


Fictitious solution:

include unset($path);

This would have worked if unset returned the value of the unsetted variable. It doesn't though. It returns void.

+2  A: 

as your using foreach, after every loop the variable is reset and reused.

for example:

foreach(glob(APP_PATH."libs/*.php") as $path)
{
    include $path;
    //$path is now set to the next variable.
}

so you only need to unset $path once at the end of the foreach loop.

for example:

foreach(glob(APP_PATH."libs/*.php") as $path)
{
    include $path;
}
unset($path);

Jobs done now, $path is totally free and clear from the memory.


have you tried the following.

function HideString(&$_)
{
    $t = $_;
    unset($_);
    return $t;
}

foreach(glob(APP_PATH."libs/*.php") as $path)
{
    include HideString(&$path);
}
RobertPitt
But the variable would still be accessible inside the included files.
Emanuil
Updated, but looks like `Delan Azabani` beat me to it :( lol
RobertPitt
A: 

To prevent that the $path is available inside the included files try to use eval("include $path;"). Im not sure what happens to vars inside eval()...

Put it into a function/method, then it is only available inside the function (namespace).

powtac
you would really use eval for a small job like that ?
RobertPitt
I would use eval() if its the onliest solution... For example this http://github.com/sebastianbergmann/phpunit/blob/master/PHPUnit/Framework/TestCase.php#L1142
powtac
the reason eval is used there is to bring a generated class into scope, them rules don't apply here.
RobertPitt
+4  A: 
Delan Azabani
This might do it :)
Emanuil
That's great to see! Good luck!
Delan Azabani
Is adding "r" to the end of the function name a common practice for indicating that the function returns a value? If yes, can you give me an example of another PHP function that have embraced this practice?
Emanuil
Not that I know of. I do not believe that suffixing `r` is common practise for functions that return values. It's just that I couldn't think of a creative name.
Delan Azabani
Thanks! I can't help but ask - are you really 14?
Emanuil
Yes. Not trolling here. Do I really look *that* old in my picture? ;)
Delan Azabani
It says 14 in your profile. I couldn't say how old / young you look in the picture :) Anyway your knowledge of programming is really impressive.
Emanuil
Thanks, I really appreciate that.
Delan Azabani