1

I'm using hooks to call a Class that is executed before controllers are called.

$hook['pre_controller'] = array(
    'class' => 'CargarInformacion',
    'function' => 'obtenerInfo',
    'filename' => 'CargarInformacion.php',
    'filepath' => 'hooks',
    'params' => ''
    );

This is the class

class CargarInformacion 
{
    function obtenerInfo()
    {
        $ci = &get_instance();
        $informacion = $ci->db->get('sitio', 1)->row();
    }
}

But I always get the same error

Trying to get property of non-object

I know there are thousands of answers realated but until now I haven't found the right one.

laviku
  • 531
  • 12
  • 32

1 Answers1

1

As codeigniter doc provided,

pre_controller

Called immediately prior to any of your controllers being called. All base classes, routing, and security checks have been done.

That's why you can't access the reference of CI superobject in pre_controller hook. You can test it by doing like this.

$hook['pre_controller'] = array(
    'class' => 'CargarInformacion',
    'function' => 'obtenerInfo',
    'filename' => 'CargarInformacion.php',
    'filepath' => 'hooks',
    'params' => 'pre'
);

$hook['post_controller_constructor'] = array(
    'class' => 'CargarInformation',
    'function' => 'obtenerInfo',
    'filename' => 'CargarInformation.php',
    'filepath' => 'hooks',
    'params' => 'post'
);

In CargarInformation.php,

class CargarInformation  {
    function __construct($foo = null) {
        $this->CI =& get_instance();
    }

    function obtenerInfo($param)
    {
        echo $param;
        echo "<pre>";
        print_r($this->CI);
        echo "</pre>";
    }
}

Therefore, try to use post_controller_constructor instead if you want to get access to the reference of CI superobject but before any method of controller calls happening.

Hope it will be useful for you.

Community
  • 1
  • 1
Arkar Aung
  • 3,554
  • 1
  • 16
  • 25