Is it possible to initialize an objects private or protected members in php with an associative array.
for example:
class TestClass
{
public $_name;
public $_age;
public function __construct(array $params)
{
??????
}
}
$testClass = new TestClass(
array(
'name' => 'Bob',
'age' => '29',
)
);
i was wondering whether there is an elegant solution - perhaps by implementing one the spl interfaces or otherwise?
You mentioned SPL. But without knowing the exact requirements for the purpose of your object, the below is about the only information I can give...
You could have your object extend the SPL built-in class
ArrayIterator
. Then, without concern for handling it in the constructor (already handled in the parentArrayIterator
class), you could import an array into your object simply like so:Keep in mind that with default
ArrayIterator
behavior, you cannot later access any of the passed array values as you would with a normal object property. You must access them as you would an array:And, internally, the passed array is stored within your object as a single private
storage
parameter. In your case, you already have all your object properties pre-defined and prepended with an underscore, so you would probably have to manually loop over$this
or$params
anyway in your constructor to set any real object properties.You could of course redefine all your child object's
ArrayIterator
inherited methods to handle your special property naming case onget
orset
, but this would seem redundant and unproductive as opposed to just looping over$params
/setting$this
anyway in your constructor.So, just looping over
$params
/setting$this
within your constructor is probably the best, most simple solution there is.See the code online for working sample here