Is there a way to set the scope of require_once() explicitly to global? Is there a way to set the scope of require_once() explicitly to global? php php

Is there a way to set the scope of require_once() explicitly to global?


Apart from "globalizing" your variable, there is no way to do this:

global $foo;$foo = 42;

OR

$GLOBALS['foo'] = 42;

Then your value should be 42 when you print it out.

UPDATE

Regarding the inclusion of classes or functions, note that all functions and classes are always considered global unless we are talking about a class method. At that point, the method in a class is only available from the class definition itself and not as a global function.


You will need to declare global in your foo.php:

<?php global $foo; $foo = 42;?>

Otherwise it's probably not possible.

You could try to play around with extract(), get_defined_vars(), global and $GLOBALS in various combinations maybe... like iterating through all defined variables and calling global on them before requiring a file...

$vars = get_defined_vars();foreach($vars as $varname => $value){  global $$varname; //$$ is no mistake here}require...

But i'm not quite sure if you get to where you want to go...


This is definitely not a "nice" work around but it would work:

function includeFooFile() {  require_once("foo.php");  foreach (get_defined_vars() as $key => $value) {    // Ignore superglobals    if (!in_array($key, array('GLOBALS','_SERVER','_GET','_POST','_FILES','_COOKIE','_SESSION','_REQUEST','_ENV'))) {      $GLOBALS[$key] = $value;    }  }}

However, your included file cannot define any functions or classes (and possibly some other things as well that I cannot currently think of) because it will result in a parse error, since you cannot nest classes or functions.

EDIT apparently you can include functions in your file. I had always thought you couldn't but after testing it seems that you can.