Framework: Method to Clone Collections

Created on 5 Sep 2016  路  8Comments  路  Source: laravel/framework

  • Laravel Version: 5.2.8
  • PHP Version: 5.6.25
  • Database Driver & Version: not applied

    Description:

One method that is important do Illuminate/Collection have is clone(), this method generate a copy of the current collection.

Can anyone make some comments here why or why not this is a bad idea ?

Thanks.

Steps To Reproduce:

$collection = collect();
$clone = $collection->clone();
// or
$clone = clone $collection;

Most helpful comment

Why are you not able to use the $clone = clone $collection; example?

For me that works:

$collection = collect([1, 2, 3]);

    dd(
        $collection,
        clone $collection
    );

image

Or is this a feature request?

If it is, its pretty simple to complete with a macro;

\Illuminate\Support\Collection::macro('clone', function() {
        return clone $this;
    });

All 8 comments

Why are you not able to use the $clone = clone $collection; example?

For me that works:

$collection = collect([1, 2, 3]);

    dd(
        $collection,
        clone $collection
    );

image

Or is this a feature request?

If it is, its pretty simple to complete with a macro;

\Illuminate\Support\Collection::macro('clone', function() {
        return clone $this;
    });

@alexbowers this works with simple internals, but test this with objects that are passed has references, the clone method obviously don't copy the objects, only the references, is correct to copy all object's in the collection or mantain the references to them original objects ?

I'd say if you were cloning a reference, you'd expect it to still reference the same thing. A clone should be an exact replica.

I'd say if you were cloning a reference, you'd expect it to still reference the same thing

That's not the definition of cloning.

Cloning a collection will give a shallow clone. Are you asking for a way to do a deep clone?

You could always traverse the object and clone each item individually if it is itself an object. Doing this recursively would be a deep clone I guess

@GrahamCampbell @alexbowers yes deep-copy is what I mean, any chance to have some native stuff in Laravel for this ? or is more application like feature ?

Well I'm going to close this Issue since it's not a bug report, I suggest that you open a PR with the suggested changes or open an issue on the internals repository, it's where we keep all our discussions & feature requests.

Thanks for the suggestion though :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

RomainSauvaire picture RomainSauvaire  路  3Comments

shopblocks picture shopblocks  路  3Comments

YannPl picture YannPl  路  3Comments

lzp819739483 picture lzp819739483  路  3Comments

Anahkiasen picture Anahkiasen  路  3Comments