Josh Jackson Josh Jackson - 20 days ago 5
PHP Question

Variable defined in index not accessible

I have a php framework in which I route all requests through an index file. In the index file I have:

index.php

$module = new module();
$module->SetName("user");
$call = new call();
$call->SetController("login");


I then do some processing to find the requested controller file. Once found, I do

$call->LoadController()


This method requires the file specified by the module and call. In this case it will do
require_once CONTROLLERS . "user/"."login.php"


All good up to here. In the loaded controller file I do

controllers/user/login.php
$call->SetView("login")


I get a php error of
undefined variable $call


I'm not sure why?

Answer

$call is not known inside of LoadController() because it is in global scope. The included controller file shares the scope of LoadController. This is why you can not use $call in your controller file. There are three solutions: You could use "global" keyword in LoadController() so $call is known in LoadController() and in the included controller file:

class module
{
   public function LoadController()
   {
      global $call;
      require_once('controllers/user/login.php');
   }
}

But this solution is ugly.

The second solution is to use $this->SetView() instead of $call->SetView() in included controller file. The disadvantage in this solution is that you have several $this in included files and you don't know what class is meant with $this. Still better than the first solution.

The third solution is to use Singleton pattern. You only need one object of the class module and it will prevent many trouble for you. Then you can call SetView() from whereever you want to without the problems of global variables and unknown scopes. You would call SetView() like this: module::getInstance()->SetView(). Check out singleton pattern: https://duckduckgo.com/?q=singleton+pattern