【问题标题】:Cannot get property from object $this variable无法从对象 $this 变量中获取属性
【发布时间】:2018-07-11 09:39:30
【问题描述】:

我真的对这种情况感到困惑。我想从我的类中的函数中获取数据,该函数由 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();

看起来不错,但是当我尝试获取$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
[“属性”:“ActiveRecord\Model”:私有]=> 数组(2){ ["bag_id"]=> 整数(160) [“口袋类型”]=> string(0) "" } ["__dirty":"ActiveRecord\Model":private]=> 数组(0) { } ["__readonly":"ActiveRecord\Model":private]=>
bool(false) ["__relationships":"ActiveRecord\Model":private]=>
数组(0) { } ["__new_record":"ActiveRecord\Model":private]=>
布尔(假)}

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

【问题讨论】:

  • 我的猜测是问题出在变量范围上。如果pocket_types 在父类上是私有的,那么你就不能访问它
  • @DimitrisFilippou 我从同一个类 (Bag) 函数中获得 pocket_types... 我可以在那里获得 bag_id!但我无法获得pocket_type。难以置信
  • 你能用完整的类定义更新你的代码吗?
  • @DimitrisFilippou 这是完整的类定义代码。我已经删除了所有其他要调试的代码,但我还是得到了一个错误
  • @DimitrisFilippou 它是使用数据库中的 Activerecord\Model (ORM) 自动创建的

标签: php undefined phpactiverecord


【解决方案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

【讨论】:

  • 是的,我检查了文档并意识到了这一点,谢谢。但这很奇怪 - 当我尝试在那里 $this->read_attribute('pocket_types') 时,我也得到一个错误:Uncaught exception 'ActiveRecord\UndefinedPropertyException' with message 'Undefined property: Bag->pocket_type in ...Bag.php(7): ActiveRecord\Model->read_attribute('pocket_type')... 该死的 php.activerecords :) 也许函数的另一个名称是这种情况的最佳解决方案
  • pocket_types 不是pocket_type 不是吗?
  • 哦,是的,我的错误在这里)现在它工作了,再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-08
  • 2016-06-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多