我对这种情况真的很困惑。我想从我的类中由 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 时,出现错误
。这个字段是绝对存在的,就像一个字段Notice: Undefined property: Bag::$pocket_types in models/Bag.php on line 21
->pocket_typesbag_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
。
关于php - 无法从对象 $this 变量获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51282117/