I'm trying to write some generic code for setting the values of an object taking values from a passed-in array.
The Reflection API appeared ideal for this, and I wrote this function:
Code:
private function _loader($array)
{
$rc = new ReflectionClass(get_class($this));
$properties = $rc->getProperties();
foreach ($properties as $property)
{
$key = $property->getName();
// check for the property in the passed-in array...
if (array_key_exists($key, $array) && !is_null($array[$key]))
{
echo("setting value of $key");
// element found...
$property->setValue($this, $array[$key]);
}
}
}
however, I get an error on the $property->setValue($this, $array[$key]), being that you cannot set private/protected variables using the Reflection API. However, I am just trying to set private values from
within the class - hence me passing in $this. Is there any way of doing this with the reflection API, or do I have to use eval (which I don't want to do, because it's not very elegant at all).