I created this library:
class Header
{
function __construct()
{
$this->user();
}
function user()
{
开发者_JAVA技巧$my_user = $this->session->userdata('my_user'); // True or False
if($my_user)
{
echo 'user!';
}
}
}
/* End of file Header.php */
I call it in any controller:
public function __construct()
{
parent::__construct();
$this->load->library('Header');
}
The error:
Fatal error: Call to a member function userdata() on a non-object in ** on line 11
I don't know what is the problem, I'm sure that the library session is called (I call it from autoload)... what can I do? When this library code is in any controller it works great, the problem is anywhere with custom library.
That won't work in a library, see the documentation.
$CI =& get_instance();
$CI->load->library('session');
$my_user = $CI->session->userdata('my_user');
The issue you're running into is that in a library, the CI object (this) isn't loaded, you need to get it.
So try this (a reference to the CI object is stored in the $CI variable):
class Header
{
private $CI;
function __construct()
{
$this->user();
if (!isset($this->CI))
$this->CI =& get_instance();
}
function user()
{
$my_user = $this->CI->session->userdata('my_user'); // True or False
if($my_user)
{
echo 'user!';
}
}
}
In the constructor, you get a reference to the CI object, and store that in the $CI variable, then you use that when you want to access its methods etc.
精彩评论