Hi Zoltán,
On Mon, Apr 17, 2023 at 11:13 PM Zoltán Fekete <fekzol.13...@gmail.com>
wrote:

> Hey,


> > public function withStatus($code, $reasonPhrase = ''): Response
> > {
> >     return clone $this {
> >         $this->statusCode = $code;
> >         $this->reasonPhrase = $reasonPhrase;
> >     };
> > }
>
> How to refer to any of the properties of the current instance? Let's say
> this:
>
> ```
> class Foo {
>     protected int $code;
>     protected string $message;
>     public function withStatus($code, $message): Foo {
>         return clone $this {
>             $this->code = $code; // so far so good
>             // Which $this->message is what?
>             $this->message = "cloned: (" . $this->message . ")" . $message;
>         }
>     }
> }
> ```


Yes, it's true that it looks weird that $this is present in two places with
two different meanings, but that's just because we are cloning $this. If we
were cloning $object, it would be clearer.
$this inside the braces is referring to the new object after it was cloned,
after __clone() was executed, if defined.
The old instance data is already copied over, no real need to reference
that.

Maybe we can think about it a bit more and improve the idea. I'm
thinking we can have a closure/callable or an instance method reference
instead of a block of code.
Also, that might be preferable, as there is a natural way to either use
closure with "use" or pass parameters.
I don't like too much how $code and $message are referenced inside the
block of code... maybe it's not an issue.
Also, I'm not really sure how easy it would be to model this behavior, to
have a block of code where $this would reference something else than
outside of it.

Regards,
Alex

Reply via email to