David Ericsson
David Ericsson

Reputation: 2660

Global variable is not working as expected in PHP

I'm trying to make my own simple framework in PHP. It's going OK but I'm running into a problem.

I redirect everything back to my index.php, and from there I start loading classes and functions. I split up the url into segments, which works fine, until I want to use the segments in a class.

I have a main controller class like this:

class SimpleController {
    
    public function __construct()
    {
        global $uri;
        print_r($uri);
    }
  }  

It prints out the $uri variable just fine, however when I make a new controller for lets say my homepage, I do this:

class home extends SimpleController{

private $template = 'home'; // Define template for this page

public function __construct()
{
    parent::__construct();
}
    
public function index()
{        
    
 
   print_r($uri);
  $view = new View($this->template); // Load the template
     
}}

Now it gives me an error, undefined variable. How is this possible, since I made it global in the parent constructor?

Upvotes: 0

Views: 287

Answers (4)

m4t1t0
m4t1t0

Reputation: 5721

As @yes123 says, your design is very bad, you should avoid the use of global variables. Otherwise, you need to use global in every function when you want to use a global variable, change your code to this:

public function index()
{
  global $uri;       
  print_r($uri);
  $view = new View($this->template); // Load the template

}

Upvotes: 0

Karoly Horvath
Karoly Horvath

Reputation: 96266

How is this possible, since i made it global in the parent constructor?

It's a new scope, so you have to mark it as global (global $uri;) again, if you want to access it.

But it's a bad design, use a member or class variable.

Upvotes: 0

Dillen Meijboom
Dillen Meijboom

Reputation: 964

Don't use "global" in PHP.. Just use a public variable in your controller;

New code:

abstract class SimpleController {
    public $uri;

    public function __construct($uri)
    {
        $this->uri = $uri;
    }
}

class home extends SimpleController{
    private $template = 'home'; // Define template for this page

    public function index()
    {
        $this->uri; //This is the URI
        $view = new View($this->template); // Load the template
    }
}

To create your controller just use:

$controller = new home();
$controller->uri = "URI";
$controller->index();

EDIT: Removed constructor from home, when you want to use this also pass $uri.

Upvotes: 2

dynamic
dynamic

Reputation: 48101

Thats a bad design. You should not rely on global state. Instead pass $uri in the costructor of your home.

Upvotes: 1

Related Questions