Why clone an object in yii2 pagination

Here in the pagination doc they use $ countQuery = clone $ query; What for? It works without cloning and produces the same sql queries as a result as the clone. Help me find the difference.

+3


source to share


2 answers


The advantage of clone over creating a new object is that all properties will be copied to the new object instead of resetting them. This is very useful when using the query builder. In the example with the official doc we have:

$query = Article::find()->where(['status' => 1]);
$countQuery = clone $query;

      



If you get a dump from $query

and $countQuery

, you can see $countQuery

- this is a new object, similar to $query

as well status=>1

. In these cases, we use a clone to have two nearly identical queries with slight differences. Thus, you can have multiple behaviors from Query Object

. This will be more useful if you have complex query builder objects that might be slightly different from your existing query. For example, you need to have union

. You don't want to overwrite your object Query

, do you? So the best way is to get a clone from an existing request and then change its behavior.

+1


source


If you meant why you should clone an object and not iterate over it, the answer is that calling the count function of an object can change its internal state. If you reuse the same object, it can give unexpected results.



0


source







All Articles