Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Preserve scope when calling a function

Tags:

I have a function that includes a file based on the string that gets passed to it i.e. the action variable from the query string. I use this for filtering purposes etc so people can't include files they shouldn't be able to and if the file doesn't exist a default file is loaded instead. The problem is that when the function runs and includes the file scope, is lost because the include ran inside a function. This becomes a problem because I use a global configuration file, then I use specific configuration files for each module on the site. The way I'm doing it at the moment is defining the variables I want to be able to use as global and then adding them into the top of the filtering function.

Is there any easier way to do this, i.e. by preserving scope when a function call is made or is there such a thing as PHP macros?

Edit: Would it be better to use extract($_GLOBALS); inside my function call instead?

Edit 2: For anyone that cared. I realised I was over thinking the problem altogether and that instead of using a function I should just use an include, duh! That way I can keep my scope and have my cake too.

like image 584
Joshua Avatar asked Oct 03 '08 02:10

Joshua


1 Answers

Edit: Okay, I've re-read your question and I think I get what you're talking about now:
you want something like this to work:

// myInclude.php
$x = "abc";

// -----------------------
// myRegularFile.php

function doInclude() {
    include 'myInclude.php';
}
$x = "A default value";
doInclude();
echo $x;    // should be "abc", but actually prints "A default value"

If you are only changing a couple of variables, and you know ahead of time which variables are going to be defined in the include, declare them as global in the doInclude() function.

Alternatively, if each of your includes could define any number of variables, you could put them all into one array:

// myInclude.php
$includedVars['x'] = "abc";
$includedVars['y'] = "def";

// ------------------
// myRegularFile.php
function doInclude() {
    global $includedVars;
    include 'myInclude.php';
    // perhaps filter out any "unexpected" variables here if you want
}

doInclude();
extract($includedVars);
echo $x;        // "abc"
echo $y;        // "def"

original answer:

this sort of thing is known as "closures" and are being introduced in PHP 5.3

http://steike.com/code/php-closures/

Would it be better to use extract($_GLOBALS); inside my function call instead?

dear lord, no. if you want to access a global variable from inside a function, just use the global keyword. eg:

$x = "foo";
function wrong() {
    echo $x;
}
function right() {
    global $x;
    echo $x;
}

wrong();        // undefined variable $x
right();        // "foo"
like image 115
nickf Avatar answered Oct 13 '22 00:10

nickf