Cast object for stdClass

I have a database model with __get and __set functions that prevent the dynamic creation of properties (to prevent input errors):

 class UserModel { public $Name; public $LanguageCode; // fe "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 the template engine. Therefore, I want to run array_map in an array and add an additional LanguageText property that will 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'm trying to add a dynamic property. I tried this: $v = (object)$v; to apply the UserModel object to stdClass , but this type has not changed. Any ideas on how to abandon UserModel without having to serialize / unserialize the data?

I am using PHP 5.3.5

+4
source share
1 answer

You need to do a double throw to do what you want ...

 $v = (object)(array)$v; 
+15
source

Source: https://habr.com/ru/post/1492159/


All Articles