First a general comment on cloning.

Nothing bad happens if we allow cloning other than a performance hit.
But only if we ensure that immutable objects are identified by value and
not by the usual object hash. In case of the latter, as it is
implemented right now, you end up with an exact copy but different, due
to the usual object hash.

Now this might not be as bad as it sounds but it kind of makes the hole
point of having immutable value objects less useful. And heck, we want a
proper implementation of this.

Hence, even if we allow cloning, at least an E_INFO should be emitted if
done so in order to be able to spot those useless cloning operations in
your code easily.

Note that changing an existing class to an immutable class is always a
breaking change, no matter what. Simply because you do not know what the
libraries and applications that depend on your library are doing with
that class right now. ;)

All of this are reasons why I generally make the __clone callback of my
value objects private or protected. It ensures that nobody is able to
clone them without running into problems. It's all about encapsulation
and only providing the behavior for the objects that is required.

I am and will be a strong proponent of disallowing cloning on immutable
objects. There is not a single argument why this should work.

On 9/7/2016 8:57 AM, Michał Brzuchalski wrote:
> AFAIK CoW in case of objects would be impossible to implement.
> 

Nothing is impossible. :)

We have full access to the real object inside of zend_std_write_property
and can easily clone it, perform the desired changes and return without
affecting anyone.

I am not 100% sure how to do this without fiddling around a bit.

@nikic and @afaults: I am really sorry to bother you both but you guys
simply know the PHP source endlessly good. What do you think, would it
be possible to implement copy-on-write for an object as we have it with
our scalar and compound types?

    final class A {
      public $p;
    }

    $a = new A;
    $b = $a;

    var_dump($a === $b); // bool(true)

    $b->p = 1;

    var_dump($a === $b); // bool(false)

It's only about writing to existing properties.

-- 
Richard "Fleshgrinder" Fussenegger

Attachment: signature.asc
Description: OpenPGP digital signature

Reply via email to