Yii2: Clone problem

Created on 24 Jul 2018  路  4Comments  路  Source: yiisoft/yii2

Is common in PHP, but I think that Yii can fix it in magic method __clone

What steps will reproduce the problem?

In my case, with Data Provider and its Querys

$dataProvider2 = clone $dataProvider1;
$query1 = $dataProvider1->query;
$query2 = $dataProvider2->query;

$query1->select(['id']);
$query2->select(['name']);

print_r($query1->select); // 'name' should by 'id'
print_r($query2->select); // 'name'

print_r($query1 === $query2); // are same object

What is the expected result?

That when I clone an object, its attributes are cloned as well.

What do you get instead?

For the moment, I have to clone the attribute I need to use (query).
$query2 = clone $dataProvider2->query;
But it could affect other non-cloned parts.

It is also not efficient to clone all objects manually every time you want to make a clone.

I think Yii could overwrite the __clone magic method and solve the problem.

In PHP web

public function __clone() { 
    foreach ($this->varName as &$a) { 
        foreach ($a as &$b) { 
            $b = clone $b; 
        } 
    } 
}

Additional info

http://php.net/manual/en/language.oop5.cloning.php

ready for adoption

Most helpful comment

@samdark It does not change the fact that Query should be also cloned - current behavior is tricky and unintuitive.

All 4 comments

That doesn't sound like it's a good idea to do for all objects by default and I'm not sure it's a job of the framework to provide such functionality.

@samdark It does not change the fact that Query should be also cloned - current behavior is tricky and unintuitive.

Yes. That could be adjusted.

thanks

Was this page helpful?
0 / 5 - 0 ratings