2014-07-11 3 views
0

나는 같은 클래스의 다른 객체들을 포함하고있는 stdClass 클래스의 객체를 가지고있다. 해당 개체의 모든 stdClasses를 'AppCategory'라는 사용자 지정 클래스로 어떻게 바꿉니 까?stdClass를 사용자 정의 클래스로 재귀 적으로 변환하려면 어떻게해야합니까?

I 클래스로 객체를 캐스팅이 기능을 발견했습니다, 그러나 반복적으로 작동하지 않습니다 :(그것은 단지 기본 개체의 이름을 변경하지 그것은 아이들의

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

답변

0

어쩌면이 같은 :.

foreach($object as &$prop) { 
    if(is_object($prop)) { 
     $prop = cast($prop, $class); 
    } 
}  

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