I'm not 100% sure what kind of usage of the private $data
variable you might be doing, so my tendency here would be to take a slightly different approach.
Instead of grouping all your data fields inside a single private variable of the object, I would make each field a private variable itself, ie:
class Item
{
private $db;
private $AltItem1;
private $AltItem2;
...
etc.
This would immediately solve your problem with having publicly available data fields as well, as you could simply declare such fields as a public member. Public members don't require a getter and a setter, so you wouldn't have to worry about that... you could just access them through $this->price
(internally), or $item->price
(externally). Saves you some code. And it would be a quick modification of your populate()
function to set all your new properties, as all you'd have to do would be to set $this->$$key
instead of $this->data[$key]
.
Now, with your use of __set()
and __get()
, it looks like you want to be able to access the private $data
member even from outside the object. There's no reason you can't continue that by having each field declared separately private as well. __set()
and __get()
will operate exactly the same way, you'd just need a minor adjustment, ie:
public function __get($varname)
{
if ($this->$varname !== null) return $this->varname;
error_log("Invalid key '$key'");
return null;
}
As a final bonus, extending the class becomes easier, because you don't have to redeclare all the fields in their entirety if you want to override the $data
property. You simply add the new fields of your children as new private members.
So I'm not sure if that makes your life easier, but I think that would be my approach.