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?
The require_once keyword is used to embed PHP code from another file. If the file is not found, a fatal error is thrown and the program stops. If the file was already included previously, this statement will not include it again.
require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page). So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example.
require_once() function can be used to include a PHP file in another one, when you may need to include the called file more than once. If it is found that the file has already been included, calling script is going to ignore further inclusions. If a. php is a php script calling b.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With