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
The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified.
Within class methods non-static properties may be accessed by using -> (Object Operator): $this->property (where property is the name of the property). Static properties are accessed by using the :: (Double Colon): self::$property .
You have to do a double cast to do what you want...
$v = (object)(array)$v;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With