0

I have the testClass class and I want to create new object from unserialized object in its constructor. Is it possible? Something like this:

class testClass {
    public __constructor($id) {
        $queryData = DB::query(sql);
        $object = unserialize($queryData);
        $this = $object;
    }
}

In this way the rest of the code won't bother how the object is constructed:

$object = new testClass(3);
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • 1
    You can't.... $this already exists and is actively executing at the point where you're trying to metamorphose it; but you can take a factory approach – Mark Baker Oct 19 '13 at 18:34
  • @MarkBaker, thanks, I'd appreciated if you provided an example as an answer, if possible – Max Koretskyi Oct 19 '13 at 18:35
  • [What is a factory design pattern in php?](http://stackoverflow.com/questions/2083424/what-is-a-factory-design-pattern-in-php/) – Mark Baker Oct 19 '13 at 18:38

2 Answers2

0

unserialize should give you the object already.

$object = new TestClass();
$queryData = serialize($object);
$object2 = unserialize($queryData);
// object2 is now a copy of object
Halcyon
  • 57,230
  • 10
  • 89
  • 128
0

As Mark Baker and Frits van Campen suggested, I used factory:

public static function factory($idText = NULL, $rawText = NULL, $properties = NULL) {
    if ($idText === NULL) {
        return new Article($idText, $rawText, $properties);
    } else {
        $fetchedObject = self::fetchStoredObject($idText);
        if ($fetchedObject !== NULL) {
            return $fetchedObject;
        } else {
            throw new Exception('Article with ID ' . $idText . ' does not exist');
        }
    }
}
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488