【问题标题】:How do I convert stdClass to my custom class recursively?如何递归地将 stdClass 转换为我的自定义类?
【发布时间】:2014-07-11 15:09:40
【问题描述】:

我有一个 stdClass 类的对象,它包含同一类的其他对象。如何将该对象的所有 stdClasses 重命名为名为“AppCategory”的自定义类?

我发现这个函数可以将对象转换为类,但它不能递归工作:(它只重命名主对象,而不是子对象。

function cast($object, $class) {
    if( !is_object($object) ) 
        throw new InvalidArgumentException('$object must be an object.');
    if( !is_string($class) )
        throw new InvalidArgumentException('$class must be a string.');
    if( !class_exists($class) )
        throw new InvalidArgumentException(sprintf('Unknown class: %s.', $class));
    if( !is_subclass_of($class, get_class($object)) )
        throw new InvalidArgumentException(sprintf(
            '%s is not a descendant of $object class: %s.',
            $class, get_class($object)
        ));

    /**
     * This is a beautifully ugly hack.
     *
     * First, we serialize our object, which turns it into a string, allowing
     * us to muck about with it using standard string manipulation methods.
     *
     * Then, we use preg_replace to change it's defined type to the class
     * we're casting it to, and then serialize the string back into an
     * object.
     */



    logToFile(print_r($x, true), false, $_SERVER['DOCUMENT_ROOT'].'/administrator/components/com_apps/log.php', 'a');



    return unserialize(
        preg_replace(
            '/^O:\d+:"[^"]++"/', 
            'O:'.strlen($class).':"'.$class.'"',
            serialize($object)
        )
    );

【问题讨论】:

    标签: php object recursion casting stdclass


    【解决方案1】:

    可能是这样的:

    foreach($object as &$prop) {
        if(is_object($prop)) {
            $prop = cast($prop, $class);
        }
    }    
    
    return unserialize(
            preg_replace(
                '/^O:\d+:"[^"]++"/', 
                'O:'.strlen($class).':"'.$class.'"',
                serialize($object)
            )
        );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-29
      • 2012-02-14
      • 2010-09-26
      • 1970-01-01
      • 2023-01-13
      • 1970-01-01
      • 2019-07-18
      相关资源
      最近更新 更多