php - Get (overloaded) array values set using __set as class properties when returning the object
one text
I has an attributes array in the model. I am setting it's values using __set
and have __get
implemented to return values from it. Like so:
protected $attributes = [];
public function __set($key, $val){
$this->attributes[$key] = $val;
}
public function __get($key){
return $this->attributes[$key] ?? throw new Exception("attribute not found");
}
Now when I do this:
$object = new Model;
$object->name = "Model name";
$object->some_other_prop = "some other prop";
return ["data" => $object];
I want the result to be:
"data" : {
"name" : "Model name",
"some_other_prop" : "Some other prop",
}
I have tried __toString
method, by returning a json_encoded attributes array, but when assigned to data, it returns an empty object.
This is the result I am getting:
"data" : {}
I am trying to learn implementing an active record style model, and I know this is possible in Laravel. I have gone through Laravel's code base and I could not figure out how they did this.
Any help will be appreciated.
Source