代码之家  ›  专栏  ›  技术社区  ›  MrSmile cashews

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

  •  1
  • MrSmile cashews  · 技术社区  · 7 年前

    我真的对形势感到困惑。我想从我的类中的函数(由ActiveRecord模型创建)获取数据。这里是一个类:

    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); 在函数中:

    对象(包)16(6)[“错误”]=>空
    [“attributes”:“activerecord\model”:private]=>数组(2){ [“Bag_ID”]=> 利息(160) [“口袋类型”]=> 字符串(0)“[”uu dirty“:”activerecord\model“:private”=>数组(0)[”u readonly“:”activerecord\model“:private”=>
    bool(false)[“uu relationships”:“activerecord\model”:private]=>
    数组(0)[“uu new_record”:“activerecord\model”:private]=>
    布尔(假)

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

    1 回复  |  直到 7 年前
        1
  •  1
  •   Lee Kowalkowski    7 年前

    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

    推荐文章