将对象转换为stdClass

时间:2013-07-18 18:59:43

标签: php

我有一个带有__get__set函数的数据库模型,它们阻止动态创建属性(以防止输入错误):

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");
    }
}

现在,我有一个UserModel个实例($users)数组,我想传递给模板引擎。因此,我想在数组上运行array_map并添加一个其他属性LanguageText,以便在模板中使用。

$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

当然,行$v->LanguageText = ...会抛出错误,因为我尝试添加动态属性。我试过这个:$v = (object)$v;UserModel对象强制转换为stdClass,但类型不变。任何想法如何摆脱UserModel而不必序列化/反序列化数据?

我正在使用PHP 5.3.5

1 个答案:

答案 0 :(得分:17)

你必须做双重演员才能做你想做的事......

$v = (object)(array)$v;