0

I'm a codeigniter beginner. I'm using version 2.0.2 with a local server (php 5.3) and I have a start controller with code like this (just for testing obviously):

<?php  

class Start extends CI_Controller
{
    var $base;
    function _construct()
    {
        parent::_construct();
        $this->base = $this->config->item('base_url');
    }   
    function hello()
    {
        $data['base'] = $this->base;
        print_r ($data);
    }


}

When I navigate to the hello function the $data['base'] array element is empty. Why should that be when the construct function has populated it with 'base_url' from the config file?

Seems that the variable $base is not available outside the construct function but I can't understand why or how to fix. Can anyone advise please?

1
  • 3
    did you try with a fake string? $this->base = 'test'; on the constructor Commented Jun 20, 2011 at 15:32

3 Answers 3

4

Your constructor should be __construct() (2 underscores).

function __construct()
{
   parent::__construct();
   $this->base = $this->config->item('base_url');
}

Also, as other people have mentioned, if you load the 'url_helper', you can get the base_url by calling base_url().

$this->load->helper('url');
$this->base = base_url();
Sign up to request clarification or add additional context in comments.

1 Comment

Many thanks - it was the two underscores that fooled me. Everything then fell into place
1

Did you know you can do

$this->load->helper('url');
$base = base_url();

Or even in the view:

<?php echo base_url(); ?>

Comments

1

Use it like this:

class Start extends CI_Controller
{
 private $base = ''; 
 function _construct()
 {
    parent::_construct();

    $this->base = $this->config->item('base_url');
 }

 function hello()
 {
    $data['base'] = $this->base;
    print_r ($data);
 }
}

Or in the autoload.php configure:

$autoload['helper'] = array('url');

and then you can use base_url(); everywhere in your code.

Comments

Your Answer

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