Skip to content
Advertisement

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement