How do you copy a PHP object into a different object type

后端 未结 5 1834
梦毁少年i
梦毁少年i 2020-12-20 15:50
  1. New class is a subclass of the original object

  2. It needs to be php4 compatible

5条回答
  •  感动是毒
    2020-12-20 16:48

    You can do it with some black magic, although I would seriously question why you have this requirement in the first place. It suggests that there is something severely wrong with your design.

    Nonetheless:

    function change_class($object, $new_class) {
      preg_match('~^O:[0-9]+:"[^"]+":(.+)$~', serialize($object), $matches);
      return unserialize(sprintf('O:%s:"%s":%s', strlen($new_class), $new_class, $matches[1]));
    }
    

    This is subject to the same limitations as serialize in general, which means that references to other objects or resources are lost.

提交回复
热议问题