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?

gen_Eric
228k42 gold badges304 silver badges343 bronze badges
asked Jun 20, 2011 at 15:26
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();
answered Jun 20, 2011 at 17:25
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(); ?>
answered Jun 20, 2011 at 16:00

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.

answered Jun 20, 2011 at 16:59

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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