I'm looking for a way to set the scope of require_once()
to the global scope, when require_once()
is used inside a function. Something like the following code should work:
file `foo.php':
<?php
$foo = 42;
actual code:
<?php
function includeFooFile() {
require_once("foo.php"); // scope of "foo.php" will be the function scope
}
$foo = 23;
includeFooFile();
echo($foo."\n"); // will print 23, but I want it to print 42.
Is there a way to explicitly set the scope of require_once()
? Is there a nice workaround?
As the scope is explicitly defined where you use
require
and the like, you would need to specify what to do with the variables inside the scope of the function:This example takes care of both, variables and references which might be what you're looking for. Demo. Please note that
require_once
would only work once and would only define the variables once.This is definitely not a "nice" work around but it would work:
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.
I haven't tried it (since using global vars is a bad idea tbh) but this could potentially work:
Alternatively you can just do it manually:
Pending on your exact requirements, you could use constants. Require your file in the global scope, but inside it set a constant.
IE file.php:
Then anywhere in your script just use
MY_CONSTANT
to refer to the value, you won't be able to edit once it's been set though. Other than that, you could globalize your variable as the other answer says, but it's not 100% clear what you're trying to achieve other than simply retrieving a value from the included file? In which case constants should be fine.Update: Now you've explained that you want an objects properties to be available everywhere, I suggest you look into creating a static class, which once instantiated in your global scope can be used anywhere in your app. Read the linked manual page, it has a bare-bones example.
You can use this hacky function I wrote:
It moves any newly defined vars back into global space when the include file returns. There's a caveat that if the included file includes another file, it won't be able to access any variables defined in the parent file via
$GLOBALS
because they haven't been globalized yet.Apart from "globalizing" your variable, there is no way to do this:
OR
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.