类属性数组,不能使用$ this来设置值

时间:2017-02-26 04:06:24

标签: php class object instantiation

在下面的类中,实例化时,我收到以下错误:

' $这'第12行的代码中的(T_VARIABLE) ' default_timestamp' => $这 - > _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();

1 个答案:

答案 0 :(得分: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();