include() within function - making included vars global?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
sargant
Forum Newbie
Posts: 1
Joined: Thu Jan 22, 2004 9:08 am

include() within function - making included vars global?

Post by sargant »

Hello,

I have a "customised" include function that records information every time a file is included. A basic boiled down version is:

Code: Select all

function include_custom($include) {
  global $include_count;
  $include_count++;
  include($include);
}
The included files add all manner of variables to the main script. The problem comes with the fact they are included as local variables for the function, when they are needed outside.

Is there any way of "setting" a function to treat all internal variables, including newly declared ones, as globals?

Any hints whatsoever would be greatly appreciated.
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Re: include() within function - making included vars global?

Post by McGruff »

You can return values from an included file. If there are several of them you'll need to put them in an array and return that.

Code: Select all

// in the included file:
$stuff = array();

// create a numerical array:
$stuff[] = $var1;
$stuff[] = $var2;
// .. etc

// .. or associative:
$stuff[${$var1}] = $var1;
$stuff[${$var2}] = $var2;
// .. etc

return $stuff;

// then return from your fn:
function include_custom($include, &$include_count) 
{
    $include_count++;
    return include($include);
}

// and in the calling script:
$stuff = include_custom($include, $include_count);
Post Reply