0

我有这个testClass类,我想在其构造函数中从未序列化的对象创建新对象。可能吗?像这样的东西:

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

这样,其余代码就不会打扰对象的构造方式:

$object = new testClass(3);
4

2 回答 2

0

unserialize应该已经给你对象了。

$object = new TestClass();
$queryData = serialize($object);
$object2 = unserialize($queryData);
// object2 is now a copy of object
于 2013-10-19T18:32:25.047 回答
0

正如建议的那样Mark BakerFrits van Campen我使用了工厂:

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');
        }
    }
}
于 2013-10-19T19:24:16.543 回答