Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

oop

php

  1. New class is a subclass of the original object

  2. It needs to be php4 compatible

like image 699
Azrul Rahim Avatar asked Sep 23 '08 05:09

Azrul Rahim


2 Answers

You could have your classes instantiated empty and then loaded by any number of methods. One of these methods could accept an instance of the parent class as an argument, and then copy its data from there

class childClass extends parentClass
{
    function childClass()
    {
        //do nothing
    }

    function loadFromParentObj( $parentObj )
    {
        $this->a = $parentObj->a;
        $this->b = $parentObj->b;
        $this->c = $parentObj->c;
    }
};

$myParent = new parentClass();
$myChild = new childClass();
$myChild->loadFromParentObj( $myParent );
like image 150
Jurassic_C Avatar answered Nov 07 '22 22:11

Jurassic_C


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.

like image 37
troelskn Avatar answered Nov 07 '22 20:11

troelskn