Josh Jackson Josh Jackson - 1 year ago 150
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:


$module = new module();
$call = new call();

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


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


I get a php error of
undefined variable $call

I'm not sure why?

Answer Source

$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;

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download