CodeIgniter PHP 访问在类中声明的变量 from 同一类中的函数


CodeIgniter PHP accessing variable declared in a class from function in same class

我正在尝试从同一类中的函数访问在类中声明的数组。我已经尝试了几种不同的方法来尝试使其工作,但我对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;

无论如何,我仍然收到"未定义的变量"错误。谢谢!

你想要$this->dates['Date1']而不是$this->$dates['Date1']。请注意dates之前缺少$

作为旁注,请确保通过定义如下所示的__construct()来正确扩展CI_Controller

class Site extends CI_Controller {
    // class properties, etc.
    function __construct(){
        parent::__construct();
    }
    // class methods, etc.
}

另一件需要注意的事情是,var从 PHP5 开始被弃用。您需要根据需要使用publicprivateprotected(编辑:当然,假设您使用的是 PHP5)。

为自己创建一个帮助程序类,该类可以执行此处所需的操作:

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

更好?