Re: Convert return to expression like throw

From: Date: Fri, 18 Mar 2022 10:46:15 +0000
Subject: Re: Convert return to expression like throw
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-117370@lists.php.net to get a copy of this message
On 18/03/2022 10:18, Florian Stascheck wrote:
function getUnreadDocuments(): int { $documents = Auth::user()?->getDocuments() ?? return 0; // actual logic of the function return 42; }
I think I'd probably reject that example as too cryptic in a code review; the mixture of assignment and control flow is hard to follow, even more so than this, which is already possible: if ( ! $documents = Auth::user()?->getDocuments() ) return 0; I can imagine some people would like it, though, particularly those used to the Perl "doSomething() or die;" idiom. The throw expression has uses in things like lambdas and match expressions, which only accept expressions not statements. I can't think of any examples where "return" would be useful in such contexts, and in fact wonder what they'd even do: return $foo = match(1) { default => return 42; } $foo = fn() => return 42; function foo() { return return 42; }  // presumably you could stack this endlessly, "return return return return 42;" function foo() { yield return 42; } Throwing exceptions already aborts the control flow, so doing so in the middle of an expression is easy to understand; having an early return in the middle of an expression is harder to understand. Regards, -- Rowan Tommins [IMSoP]

« previous php.internals (#117370) next »