Class 属性数组,不能用$this设置值
Class property array, can't use $this to set value
在下面的 class 中,当实例化时,我收到以下错误:
'$this' (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();
要用动态值初始化 class 成员,您不能直接这样做。而是使用 __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();
在下面的 class 中,当实例化时,我收到以下错误:
'$this' (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();
要用动态值初始化 class 成员,您不能直接这样做。而是使用 __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();