Yii 1.1 does not support object cloning

You better watch out
You better not cry
You better not clone Yii objects
I'm telling you why
Object cloning is coming to town not supported in Yii 1.1.

All related objects will not be cloned and today I had to fix a bug because of this:

$model2 = clone $model1;
// $model2->coolBehavior->owner !== $model2;
// $model2->coolBehavior->owner === $model1;

I've fixed this with this method by adding these lines into base model class:

public function __clone()
{
    $this->attachBehaviors($this->behaviors());
}

But there are more things that need to be reinitializen aftel cloning like events or dbCriteria so you should not clone or to do it carefully.

P.S.: Yii2 supports object cloning.

Categories: Tips

Tags: ,