Assuming I have the following class
# user.php
class User {
private $name = NULL;
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
I create a new instance of that class and after that I'm including another PHP file within index.php.
# index.php
require_once('user.php');
$u = new User;
$u->setName('Tom');
echo $u->getName(); // returns Tom
require_once('somefile.php');
Now my app is nested by requiring some more PHP files. Later in my app I'm calling another class where I try to refer to the instance of $u
;
# somefile.php
require_once('users_conroller.php');
function call() {
new usersController();
}
That is the point where the function getName()
returns NULL
.
# users_controller.php
class usersController {
public function show() {
global $u;
echo $u->getName(); // returns NULL
}
}
I guess I have some issues with variable scopes but I don't seem to get why...