2012-06-28 52 views
1

我試圖訪問同一個類中的函數在類中聲明的數組。我嘗試了幾種不同的方法來嘗試使其工作,但我相對較新的PHP。這是我的代碼CodeIgniter PHP訪問同一類中的函數的類中聲明的變量

class Site extends CI_Controller { 

    var $dates = array(
     "Task" => NULL, 
     "Date1" => NULL, 
     "Date2" => NULL, 
     "TimeDiff" => NULL 
    ); 

function index() 
{ 
    if($this->$dates['Date1'] != NULL && $this->$dates['Date2'] != NULL) 
    { 
     $this->$dates['TimeDiff'] = $this->$dates['Date2']->getTimestamp() - $this->$dates['Date1']->getTimestamp();    
    } 

    $this->load->view('usability_test', $this->$dates); 
} 

片斷我也利用全球關鍵字作爲這樣

global $dates; 

我仍然收到「未定義的變量」的錯誤,無論嘗試。謝謝!

+0

錯誤的具體部分哪個部分不明白? – hakre

回答

9

想要$this->dates['Date1']而不是$this->$dates['Date1']。請注意0​​之前沒有$

作爲一個方面說明,確保你正確地通過定義__construct()這樣的擴展CI_Controller

class Site extends CI_Controller { 

    // class properties, etc. 

    function __construct(){ 
     parent::__construct(); 
    } 

    // class methods, etc. 

} 

另一件事要注意,var被棄用PHP5的。您需要根據您的需要使用public,privateprotected(編輯:當然,假設您使用PHP5 )。

+0

這樣做,謝謝!我應該看到... –

+0

@PeteJodo:沒問題,我很高興它幫助!看到我上面的編輯了一些其他提示/建議。 –

3

自己創建一個輔助類,做你所需要的是什麼:

class MyTask 
{ 
    private $task; 

    /** 
    * @var DateTime 
    */ 
    private $date1, $date2; 

    ... 

    public function getTimeDiff() { 
     $hasDiff = $this->date1 && $this->date2; 
     if ($hasDiff) { 
      return $this->date2->getTimestamp() - $this->date1->getTimestamp(); 
     } else { 
      return NULL; 
     } 
    } 
    public function __toString() { 
     return (string) $this->getTimeDiff(); 
    } 

    /** 
    * @return \DateTime 
    */ 
    public function getDate1() 
    { 
     return $this->date1; 
    } 

    /** 
    * @param \DateTime $date1 
    */ 
    public function setDate1(DateTime $date1) 
    { 
     $this->date1 = $date1; 
    } 

    /** 
    * @return \DateTime 
    */ 
    public function getDate2() 
    { 
     return $this->date2; 
    } 

    /** 
    * @param \DateTime $date2 
    */ 
    public function setDate2(DateTime $date2) 
    { 
     $this->date2 = $date2; 
    } 
} 

這裏的關鍵點是,所有與該範圍和內容的細節是類裏面。所以你不需要關心其他地方。

作爲額外的獎勵,__toString方法可以幫助您輕鬆地將此對象集成到您的視圖中,因爲您可以只需echo對象即可。

class Site extends CI_Controller 
{ 
    /** 
    * @var MyTask 
    */ 
    private $dates; 

    public function __construct() { 
     $this->dates = new MyTask(); 
     parent::__construct(); 
    } 

    function index() 
    { 
     $this->load->view('usability_test', $this->$dates); 
    } 

    ... 

更好?

+0

是的!非常有用,非常感謝! –