2017-02-26 38 views
1

在此类中,实例化的情况下,我收到以下错误:

“$这”(T_VARIABLE)在代码第12行 “default_timestamp '=> $ this - > _ time,

我很困惑,因为当对象被实例化时,我假设$ _time可以使用,但它看起来不是。我也尝试'default_timestamp' => time(),但也抛出了一个错误。我误解了对象实例吗?

class DateTimeHandler { 

    public $_date; 
    public $_time = 'xxx'; 
    public $_datetime; 
    public $_timezone; 

    public $opts = array(
     'default_timezone' => 'America/New_York', 
     'default_timestamp' => $this->_time, 
     'formats' => array(
      'date' => 'Y-m-d', 
      'time' => 'g:ia', 
      'full' => 'Y-m-d H:i:s' 
     ) 
    ); 

    public function __construct() { 
     echo '<pre>', print_r($this->opts, true); 
    } 

} 

$d = new DateTimeHandler(); 

回答

2

要使用动态值初始化类成员,您不能直接执行此操作。而是使用__construct为同一

class DateTimeHandler { 

    public $_date; 
    public $_time = 'xxx'; 
    public $_datetime; 
    public $_timezone; 

    public $opts = array(); 



    public function __construct() { 

     $this->opts = array(
     'default_timezone' => 'America/New_York', 
     'default_timestamp' =>time(), //OR $this->_time 
     'formats' => array(
      'date' => 'Y-m-d', 
      'time' => 'g:ia', 
      'full' => 'Y-m-d H:i:s' 
     ) 
    ); 

     echo '<pre>', print_r($this->opts, true); 
    } 

} 

$d = new DateTimeHandler(); 
+0

这工作,是有一个原因,你不能直接做呢? – Naterade

+0

参考:http://php.net/manual/en/language.oop5.properties.php **初始化必须是一个常量值 - 也就是说,它必须能够在编译时进行评估,并且不能依赖在运行时信息中进行评估。** –

相关问题