-1

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...

Sofyan Thayf
  • 1,322
  • 2
  • 14
  • 26
pixelmusik
  • 510
  • 5
  • 19
  • 2
    There's alot missing. You don't ever call `call()` and you don't instantiate `usersController ` and never call `show()`. – AbraCadaver Feb 02 '18 at 14:38
  • You have a typo here : `require_once('users_controller.php');`. The `t` is missing – Syscall Feb 02 '18 at 14:41
  • You also never return anything from your function `call()`. – M. Eriksson Feb 02 '18 at 14:42
  • 2
    I would recommend that you look into [autoloading](https://stackoverflow.com/questions/7651509/what-is-autoloading-how-do-you-use-spl-autoload-autoload-and-spl-autoload-re) and [dependency injection](https://code.tutsplus.com/tutorials/dependency-injection-in-php--net-28146). it will make your life easier (and your code cleaner). – M. Eriksson Feb 02 '18 at 14:44
  • Thanks for your replies, as I‘ve already said this is just a very compact version of my project and I tried to keep it as simple as possible. That’s why some calls are missing. – pixelmusik Feb 03 '18 at 04:44

1 Answers1

2

Using global for me is not really good idea for big projects. It tends to be messy. You can just pass the object $u as a parameter.

$u = ....
call( $u ); //Call call() function and pass $u object

# somefile.php
require_once('users_controller.php');
function call( $u ) {
    $c = new usersController();
    $c->show( $u );
}


# users_controller.php
class usersController {
    public function show( $u ) {
       echo $u->getName();
    }
}
Eddie
  • 26,593
  • 6
  • 36
  • 58