Failed to access global variable in included file

I have an unexpected area problem. The documentation include(also applies require_once) says that the required file must have access to the entire variable on the line in which it was needed.

For some reason, I cannot access the class created using the global scope inside the function that was needed.

Does anyone know why? I obviously missed something.

I got it using the link to $GLOBALS[], but I still want to know why it doesn't work.

UPDATE: The
error I get is:

Fatal error: Call to a member function isAdmin() on a non-object in <path>.php on <line>

The code:

$newClass = new myClass();

require_once("path to my file");

----- inside required file -----
function someFunction() {
     $newClass->someMethod(); // gives fatal error. (see above).
}
+3
source share
2 answers

, .

. , ,

:

, , .

, - , .

: , , global $newClass;, .

$newClass = new myClass();
require_once("path to my file");

----- inside required file -----
function someFunction() {
     global $newClass;
     $newClass->someMethod(); 
}

, global . , Singleton/Registry ( , ).

+3

, , . :

function a() {
    echo $b;
}

, echo $b . :

function a() {
    include 'file.php';
}

... file.php :

echo $b;

... , :

function a() {
    echo $b;
}

: , include/require, include/require, .

, .

+2

All Articles