Meetarp
Meetarp

Reputation: 2461

CodeIgniter Undefined Instance Variable

I've got a helper file that requires accessing some session data and so it looks like this (this isn't the actual file contents, but rather a simplified version with the same level of necessary detail):

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

$CI =& get_instance();

if (!is_null($CI->session->userdata('name')) {
    if ( ! function_exists('sayHi'))
    {
        function sayHi() {
            echo "Hello, " . $CI->session->userdata('name') . "!";
        }
    }
}

So let's say I'm looking at pages/home and this function is called when I submit to the same page - it's called by the model. No errors when the function is not called. When the function is called, it gives me this:

Message: Undefined variable: CI

What's going on?

Upvotes: 0

Views: 438

Answers (2)

Karoly Horvath
Karoly Horvath

Reputation: 96258

It all about scope, the function doesn't see that variable.

Put this in the function body: $CI =& get_instance();.

Upvotes: 1

Narf
Narf

Reputation: 14752

$CI is not in the visibility scope of your function code. This is a basic PHP thing, read more here: http://www.php.net/manual/en/language.variables.scope.php

Upvotes: 1

Related Questions