2011-06-20 27 views
0

我是一個codeigniter初學者。我使用的版本2.0.2與本地服務器(PHP 5.3),我有這樣的代碼開始控制器(只是用於測試明明):Codeigniter變量

<?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); 
    } 


} 

當我瀏覽到的Hello功能$data['base']陣列元素是空的。爲什麼應該在構造函數使用配置文件中的'base_url'填充它?

似乎變量$base是不可用的構造函數之外,但我不明白爲什麼或如何解決。任何人都可以提醒一下嗎?

+3

你試過用假字符串嗎? $ this-> base ='test';在構造函數 – Dalen

回答

4

您的構造函數應該是__construct()(2個下劃線)。

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

另外,其他人都提到,如果您加載了「url_helper」,你可以通過調用base_url()得到base_url

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

非常感謝 - 這是兩個下劃線,愚弄我。一切都落後了 –

1

你知道你可以甚至認爲做

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

<?php echo base_url(); ?> 
+0

非常感謝那 - 有用的東西 –

1

使用方法如下:

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); 
} 
} 

還是在autoload.php配置:

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

然後你可以使用 base_url();您代碼中的任何地方都可以使用

+0

非常感謝 - 現在更清楚 –