0

As I have read through articles, the best possible way to validate a user in all controllers of my application is to extend my own Controller that extends CI_Controller

But I can't make it work.

What I have is a members_controller that extends my MY_Controller.

in MY_Controller i have this piece of code, just to test if how am I going to utilize this.

<?php

class MY_Controller extends CI_Controller {

private $foo;

    function __construct() {
        parent::__construct();
        $this->foo = 'hello world again';
    }

}

in my members controller

<?php
class Members extends MY_Controller {
    function index() {
         $this->load->view('members');
    }
}

in my members view

i want to access this variable i just set up, but i don't know how.

i tried echoing it out like this echo $foo, like this $this->foo

but neither work. thanks much!!

4 Answers 4

5

You need to pass the variable to your view file.

    <?php
    class Members extends MY_Controller {
        function index() {
             $data = array('foo' => $this->foo)
             $this->load->view('members', $data);
        }
    }

Now you can refer to $foo inside your view. You may need to declare $this->foo as protected.

There's a video tutorial on MY_Controller that you may find useful at http://codeigniter.tv/a-10/Extending-the-core-MY_Controller-and-beyond

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

1 Comment

thanks.. i but can't do it if its a private variable.. hehe.. anyhow thank you very much!!
0

Have you tried passing the variable to the 'members view'.

$this->load->view('members',$foo);

Comments

0

You need to make $foo as protected and not private. Then you will be able to access it in your controller that extends MY_Controller.php like this: $this->foo

Comments

0

Today for the first time I used codeigniter 3. In the past I used version 2.x a lot of times. Now I can't extend CI_Controller:

application/core/MY_Controller.php

class MY_Controller extends CI_Controller {

private $data = array();

function __construct() {
    parent::__construct();
    date_default_timezone_set("Europe/Zagreb");
    $this->data['foo'] = "bar";
}

application/controllers/Welcome.php

class Welcome extends MY_Controller {

public function index() {
    $this->data['main_content'] = 'home';
    $this->load->view('template/template', $this->data); 
}

application/view/home.php (this is view loaded by $this->data['main_content'])

If I try to echo any data declared in MY_Controller, I get an error.

    <?php echo $foo; ?>

A PHP ERROR WAS ENCOUNTERED

Severity: Notice

Message: Undefined variable: foo

Filename: template/header.php

Comments

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.