0

I have created a function in my views and have tried to make a query within the php function but i do not know I am getting and unexpected error which was never been seen in my entire career can anyone help me out to get rid from this error?

Severity: Error --> Using $this when not in object context /application/views/includes/create_calendar.php 51

This is my controller

class Booking extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->helper(array("form", "url"));
        $this->load->library('session');
        $this->load->database();
    }

    public function get_calendar() {
        $this->load->view('includes/create_calendar');
    }
}

This is the file in which I am trying to run a query views/includes/create_calendar.php

function getCalender($year = '',$month = '') {  
   $sql       = $this->db->get('calendar');
   if($day == $sql->row()->day_off) { $per_off = $sql->row()->per_off; }

                        echo "<p>".$day." Off</p>";
}
1

1 Answer 1

1

In CodeIgniter usage, if you need to use one of the classes that is available in the "super object", you must first get an instance of the super object:

$CI =& get_instance();
$CI->db->get('calendar');

This DB class may not even be loaded. If that's the case, then before you use db:

$CI->load->database();

To clarify, as soon as you go in that function, you've removed $this from the variable scope, like this simple test:

class Test {

    public $foo = 'bar';

    public function index() {
        function baz(){
            return $this->foo;
        }
        echo baz();
    }
}

$t = new Test;
$t->index();

You could do something like the following, but that's really messy:

class Test {

    public $foo = 'bar';

    public function index() {
        function baz($x) {
            return $x->foo;
        }
        echo baz($this);
    }
}

$t = new Test;
$t->index();

The best thing for you to do is find another cleaner way to do what you are doing. You wouldn't normally want calls to your database and functions in your views. It goes against what MVC is all about.

Sign up to request clarification or add additional context in comments.

2 Comments

but many times i tried to call a query within the views it runs fine why did this error came in now
Based on your code, I can't tell you why. I can just tell you that this is how you get to the CodeIgniter super object when it doesn't exist. It could happen in libraries, helpers, or anywhere else too. I guess variable scope could come into play here. Being that you're inside a function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.