I'm coming from a .Net background and I'm trying to wrap my brain around a programming pattern that I'm used to but in PHP.
I've got a class with an associative array property. I'd like to "elevate" some, but not all, of the associative array keys to class-level properties. In C# I'd normally do something like this:
//C# Code
class MyClass{
private Dictionary<string, string> attributes = new Dictionary<string,string>();
//Get/Set the ID from the private store
public string ID{
get { return (attributes.ContainsKey("ID") ? attributes["ID"] : "n/a"); }
set { attributes.Add("ID", value); }
}
}
This allows my object to control default values for missing properties. In PHP I couldn't find any way to do this directly. My first workaround was to just use functions:
//PHP Code
class MyClass{
private $attributes = array();
//Get the ID
public function getID(){
return (array_key_exists('ID', $this->attributes) ? $this->attributes['ID'] : 'n/a');
}
//Set the ID
public function setID($value){
$this->attributes['ID'] = $value;
}
}
This works although the calling syntax is slightly different and I've got two methods per property. Also, the code that is consuming these objects is currently inspecting object variables so functions wouldn't be found.
Then I started going down the magic method paths of __set
and __get
on the object itself and just switch case
on the $name
that's passed in and setting/getting my local variables. Unfortunately these methods don't get invoked if you modify the underlying array directly.
So my question is, is it possible in PHP to have a class-level property/variable that doesn't get calculated until it gets used?