On Wed, Apr 26, 2023 at 3:25 AM Larry Garfield <la...@garfieldtech.com>
wrote:

> On Tue, Apr 25, 2023, at 11:23 AM, Nicolas Grekas wrote:
>
> > What about using a real closure to define the scope we need for cloning?
> > That closure would take the cloned instance as argument to allow
> > manipulating it at will.
>
> I believe someone mentioned that one previously in the thread.


Yes, Nicolas mentioned me.
I wanted to get back myself to discussing this topic more as well and find
a better solution but didn't get yet time for it.


>   The problem is that the closure would run in the scope of the object,
> not the scope of the caller.  That means if called outside the object, it
> would allow modifying private or protected properties.  The itemized list
> of values (whether an array or named-args style) would allow the engine to
> enforce access restrictions, which is a desireable feature.
>

As far as I can see, Nicolas was able to find a solution to this problem
and so far I like it:
The closure is running in the current scope where it is defined and not in
the scope of the cloned object. The cloned object is passed as the single
parameter to the closure.

The suggested clone signature for a class T would be:
- clone(T $object, callable(T $clone)): T; // calling clone as a function
- clone T $object with callable(T $clone): T; // calling clone as a
language construct
Alternatively, we can have also:
- clone T, callable(T $clone); // without "with" keyword
And improve it to allow even multiple closures to be executed:
- clone(T $object, ...callable(T $clone)): T;
- clone T $object, ...callable(T $clone): T;

IMHO, I think we should support both syntaxes.

The main reason I wanted to get back to this proposal is because > 90% of a
developer's job is to read code and the most trouble is following state
modifications of a variable.

When that variable to be investigated is a property, so far it was simple
to look for "->propertyName = <rhs expression>".
Editors would easily and clearly highlight all the write access statements
or lines (Alt+F7 in PhpStorm). I can't figure out what would be highlighted
in the non-closure syntax, especially the one with an array.

Thanks,
Alex

Reply via email to