PHP error 'non-object'

I am working on a small MVC framework in PHP for exercises. However, PHP doesn't seem to like my Controller class. The class contains an instance of the loader that loads the views:

abstract class Controller { public $load; function __construct($load) { $this->load = $load; } abstract public function index(); } 

From there, I can override the controller for all of my controllers. For instace my pointer controller:

 class Index extends Controller { public function index() { $this->load->view("hello_world"); } } 

But when I create it:

 require 'Controller.php'; require 'Load.php' require 'controllers/Index.php'; $i = new Index(new Load()); $i->index(); 

I get this error:

 PHP Fatal error: Call to a member function view() on a non-object in /var/www/controllers/Index.php on line 7 

Can you guys help me? I know that I set the load in the constructor and the load class has a method called view, so why does it give me this error? Also: loading class, only for a good grade

 class Load { public function view($filename, $data = null) { if(is_array($data)) extract($data); include ROOT.DS.'views'.DS.$filename.'.php'; } } 
+4
source share
2 answers

The problem is with this code, and this is not always obvious:

 class Index extends Controller ^^^^^ { public function index() ^^^^^ { $this->load->view("hello_world"); } } 

This is the same name and, therefore, a constructor with reverse support for PHP 4. Then the parent constructor is not called, $load not installed and the function is not defined.

Knowing this, there are many solutions, including:

 namespace DelishusCake; 

Enter namespace

This automatically fixes your problem. You need to place this on top of the file.

 class Index extends Controller { public function index($load = NULL) { isset($load) && $this->load = $load; $this->load->view("hello_world"); } } 

Make a constructor with backward compatibility PHP4

Or:

 class MyIndex extends Controller { public function index() { $this->load->view("hello_world"); } } 

Rename class

Or:

 class Index extends Controller { public function __construct($load) { parent::__construct($load); } public function index() { $this->load->view("hello_world"); } } 

Add PHP 5 constructor, call parent constructor

Keep in mind that you only need this because it is the same name. You can find a detailed description in the PHP manual on the page "Constructors and destructors" .

+8
source

You need to instantiate the parent class.

 class Index extends Controller { public function __construct($load) { parent::__construct($load); } public function index() { $this->load->view("hello_world"); } } 
+2
source

All Articles