Remix.run Logo
noduerme 8 days ago

Agree, the ... syntax feels confusing when each fn($x) in the example uses $x as the name of its argument.

My initial instinct would be to write like this:

`$result = $arr

    |> fn($arr) => array_column($arr, 'tags') // Gets an array of arrays

    |> fn($cols) => array_merge(...$cols)`
Which makes me wonder how this handles scope. I'd imagine the interior of some chained function can't reference the input $arr, right? Does it allow pass by reference?
cess11 8 days ago | parent | next [-]

You can do

     function ($parameter) use ($data) { ... }
to capture stuff from the local environment.

Edit: And you can pass by reference:

   > $stuff = [1]
   = [
       1,
     ]

   > $fn = function ($par) use (&$stuff) { $stuff[] = $par; }
   = Closure($par) {#3980 …2}

   > $fn(2)
   = null

   > $stuff
   = [
       1,
       2,
     ]

Never done it in practice, though, not sure if there are any footguns besides the obvious hazards in remote mutation.
noduerme 5 days ago | parent [-]

idk if it counts as an obvious hazard, but being able to modify the original input by reference within a chain of piped functions definitely makes it a lot harder to reason about what that sequence might be doing. Particularly since we assume that arrays are passed by reference anyway unless the function you're calling is making a shallow copy of their elements.

My feeling is that this makes the code less legible. I'd rather write 5 lines of code that mutate an object or return a copy than do a pipe this way. I'm sort of not excited to start running into examples of this in the wild.

Einenlum 8 days ago | parent | prev [-]

You can write it this way. The parameter name is arbitrary. And no, to my knowledge you can't access the var from the previous scope