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?
-
3did you try with a fake string? $this->base = 'test'; on the constructorDalen– Dalen2011年06月20日 15:32:22 +00:00Commented Jun 20, 2011 at 15:32
3 Answers 3
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();
Did you know you can do
$this->load->helper('url');
$base = base_url();
Or even in the view:
<?php echo base_url(); ?>
Comments
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.