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

Cannot get property from object $this variable

我真的很困惑。我想从 class 中由 ActiveRecord 模型创建的函数中获取数据。这里是 class:

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

好像不错,但是我尝试获取$this->pocket_types的时候出现错误Notice: Undefined property: Bag::$pocket_types in models/Bag.php on line 21。这个字段是绝对存在的,就像一个字段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) { ["errors"]=> NULL
["attributes":"ActiveRecord\Model":private]=> array(2) { ["bag_id"]=> int(160) ["pocket_types"]=> string(0) "" } ["__dirty":"ActiveRecord\Model":private]=> array(0) { } ["__readonly":"ActiveRecord\Model":private]=>
bool(false) ["__relationships":"ActiveRecord\Model":private]=>
array(0) { } ["__new_record":"ActiveRecord\Model":private]=>
bool(false) }

有人可以解释一下发生了什么吗?

您似乎创建了一个 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