无法从对象$ this变量获取属性

时间:2018-07-11 09:39:31

标签: php undefined phpactiverecord

我真的很困惑这种情况。我想从我的类中由ActiveRecord Model创建的函数中获取数据。这是一堂课:

class Bag extends ActiveRecord\Model {
    static $table_name = "bags";
    static $primary_key = 'bag_id';

    public function get_pocket_types() {
        $arr = json_decode($this->pocket_types);
        return $arr;
    }
}

我在主代码中称呼它

$bag = Bag::find_by_bag_id((int)$_GET['id']);
$types = $bag->get_pocket_types();

这似乎不错,但是尝试获取Notice: Undefined property: Bag::$pocket_types in models/Bag.php on line 21时出现错误$this->pocket_types。该字段是绝对存在的,就像字段bag_id一样。

我什至尝试调试它(在get_pocket_types()函数中):

echo $this->bag_id;
// OK

echo $this->bag_id_NOT_EXISTS;
// Fatal error: Uncaught exception 'ActiveRecord\UndefinedPropertyException' with message 'Undefined property: Bag->bag_id_NOT_EXISTS
// This is just for catch an error of REALLY not existed field

echo $this->pocket_types;
// Notice: Undefined property: Bag::$pocket_types in models/Bag.php on line 21

我在函数中叫var_dump($this);

  

object(Bag)#16(6){[“错误”] => NULL
  [“属性”:“ ActiveRecord \ Model”:专用] => array(2){       [“ bag_id”] =>       整数(160)       [“ pocket_types”] =>       字符串(0)“”} [“ __dirty”:“ ActiveRecord \ Model”:private] =>数组(0){} [“ __readonly”:“ ActiveRecord \ Model”:private] =>
  bool(false)[“ __relationships”:“ ActiveRecord \ Model”:private] =>
  array(0){} [“ __new_record”:“ ActiveRecord \ Model”:private] =>
  bool(false)}

有人可以解释会发生什么吗?

1 个答案:

答案 0 :(得分:1)

好像您已经创建了custom getter with the same name as an attribute

在这种情况下,您将需要$this->read_attribute('pocket_types')而不是$this->pocket_types

或者,将get_pocket_types重命名为get_json_decoded_pocket_types之类。