Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 771
Stephan Kulla Avatar asked Jan 23 '12 15:01

Stephan Kulla


People also ask

What does the require_once () function allow you to do?

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.

What advantage do you gain by using require_once () instead of require ()?

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.

How to require_ once in PHP?

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.


1 Answers

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.

like image 178
Mathieu Dumoulin Avatar answered Oct 09 '22 11:10

Mathieu Dumoulin