Re: [RFC] [Discussion] Clone with

From: Date: Mon, 17 Apr 2023 21:00:39 +0000
Subject: Re: [RFC] [Discussion] Clone with
References: 1 2 3  Groups: php.internals 
Request: Send a blank email to internals+get-120058@lists.php.net to get a copy of this message
Hi Zoltán, On Mon, Apr 17, 2023 at 11:13 PM Zoltán Fekete <fekzol.13ker@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

« previous php.internals (#120058) next »