Undefined $load property error after upgrading Cod

2019-03-05 22:33发布

Why I get this error after upgrading CodeIgniter from v1.7 to v2.1?

A PHP Error was encountered

Severity: Notice

Message: Undefined property: Site::$load

Filename: libraries/Website.php

Line Number: 25

Fatal error: Call to a member function library() on a non-object in C:\xampp\htdocs\travel\application\libraries\Website.php on line 25

The library application/library/website

class Website extends CI_Controller {

    public static $current_city;

    public function __construct() {

        $this->load->library('language'); // line 25
        $this->language->loadLanguage();
        $this->load_main_lang_file();
        $this->load_visitor_geographical_data();
        $this->load->library('bread_crumb');
   }
}

1条回答
家丑人穷心不美
2楼-- · 2019-03-05 23:04

You forgot to call __construct method of CI_Controller class:

public function __construct()
{
    // Call CI_Controller construct method first.
    parent::__construct();

    $this->load->library('language'); // line 25
    $this->language->loadLanguage();
    $this->load_main_lang_file();
    $this->load_visitor_geographical_data();
    $this->load->library('bread_crumb');
}

Note: If you're creating a Controller, it should be placed in application/controllers/, not in application/libraries/.

If the child (inheritor) class has a constructor, the parent constructor won't be called, because you'll override parent's constructor with the child one, unless you explicitly call parent's constructor using parent::__construct();. That's the concept of Polymorphism in object-oriented programming

If you don't call parent::__construct(); when the application controller is initializing, you'll lose Loader and Core class and $this->load would never works.

Using parent::__construct(); is needed only if you want to declare __construct() method in your Controller which it will override the parent's one.

That's true for models as well, but using parent::__construct(); in your model just logs a debug message Model Class Initialized, So if you need to know when Model is initialized (in logs), keep using that, If not, ignore it.

查看更多
登录 后发表回答