I have a database model with __get
and __set
functions that prevent dynamic creation of properties (to prevent typing mistakes):
class UserModel
{
public $Name;
public $LanguageCode; // f.e. "EN", "NL", ...
public function __get($name)
{
throw new Exception("$name is not a member");
}
public function __set($name, $value)
{
throw new Exception("$name is not a member");
}
}
Now, I have an array of UserModel
instances ($users
) that I want to pass to a templating engine. Therefore, I want to run array_map
on the array and add an additional property LanguageText
, to be used in the template.
$users = array_map(function ($v)
{
$v = (object)$v; // this doesn't help to cast away from UserModel type
$v->LanguageText = GetLanguageText($v->LanguageCode);
return $v;
}, $users);
// pass $users to templating engine
Of course the line $v->LanguageText = ...
throws an error because I try to add a dynamic property. I tried this: $v = (object)$v;
to cast the UserModel
object to stdClass
, but the type is unchanged. Any ideas how to cast away from UserModel
without having to serialize/unserialize the data?
I'm using PHP 5.3.5
You have to do a double cast to do what you want...
$v = (object)(array)$v;