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

后端 未结 5 1825
梦毁少年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:47

    A php object isn't a whole lot different to an array, and since all PHP 4 object variables are public, you can do some messy stuff like this:

    function clone($object, $class)
    {
         $new = new $class();
         foreach ($object as $key => $value)
         {
              $new->$key = $value;
         }
         return $new;
    }
    $mySubclassObject = clone($myObject, 'mySubclass');
    

    Its not pretty, and its certianly not what I'd consider to be good practice, but it is reusable, and it is pretty neat.

提交回复
热议问题