【问题标题】:Class property array, can't use $this to set value类属性数组,不能使用 $this 设置值
【发布时间】:2017-02-26 04:06:24
【问题描述】:

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

'$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();

【问题讨论】:

    标签: php class object instantiation


    【解决方案1】:

    要使用动态值初始化类成员,您不能直接这样做。而是使用__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();
    

    【讨论】:

    • 那行得通,你有什么理由不能直接做吗?
    • 参考这个:php.net/manual/en/language.oop5.properties.php 初始化必须是一个常量值——也就是说,它必须能够在编译时被评估并且不能依赖于运行时信息以便进行评估。
    猜你喜欢
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    • 2017-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多