Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast object to stdClass

Tags:

php

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

like image 963
huysentruitw Avatar asked Jul 18 '13 18:07

huysentruitw


People also ask

What is a stdClass object?

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.

How do you access the properties of an object in PHP?

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 .


1 Answers

You have to do a double cast to do what you want...

$v = (object)(array)$v;
like image 146
Orangepill Avatar answered Sep 30 '22 05:09

Orangepill