Re: Unwrap reference after foreach
| From: | Hans Henrik Bergan | Date: | Sat, 14 Aug 2021 15:17:45 +0000 |
| Subject: | Re: Unwrap reference after foreach | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-115725@lists.php.net to get a copy of this message | ||
well today you can do
foreach($it as &$value){...} unset($value);
- which is pretty close, but it will break with
$value="initial";foreach($it as &$value){...}unset($value); echo $value;
here $value will not be "initial", it will be undefined, however you *CAN*
do
$value="initial";(function()use(&$it){foreach($it as
&$value){...}unset($value);})(); echo $value;
and it will still contain "initial" and here the unset is even unnecessary,
but yeah..
usually people do not go to such lengths to get a contained variable scope
^^
On Sat, 14 Aug 2021 at 15:23, Hossein Baghayi <hossein.baghayi@gmail.com>
wrote:
> On Fri, 13 Aug 2021 at 17:59, Nikita Popov <nikita.ppv@gmail.com> wrote:
>
> > I'd like to address a common footgun when using foreach by reference:
> > https://wiki.php.net/rfc/foreach_unwrap_ref
> >
>
> Hello,
> I had a question regarding this.
> Wouldn't it be possible to limit ``
$value``'s scope
> to only foreach's
> block then discard it? Unless it was already defined elsewhere.
>
> ```
> foreach($nice_stuff as &$value) {} //we are done here and no need to keep
> value around.
>
> echo $value; // $value is Undefined here.
>
> $value = null;
> foreach($stuff as &$value) {} //we can keep the value here since it doesn't
> belong to foreach.
>
> echo $value; // prints some fancy pancy stuff
> ```
>