Skip to content

Instantly share code, notes, and snippets.

@jackfruh
Created July 3, 2016 15:25
Show Gist options
  • Save jackfruh/bd7d50a9cc949da071850bc23a4fd429 to your computer and use it in GitHub Desktop.
Save jackfruh/bd7d50a9cc949da071850bc23a4fd429 to your computer and use it in GitHub Desktop.

#Comments

In the above code, assigning the anonymous functions to variables in the same code block works, if I assign them above.

If I assign them below, no go.

I'd like to be able to define those helper functions (ShowGreatThanZero and displayoutput) elsewhere, so that the code is neat and clean.

$showGreaterThanZero = function($value) {
return $value["ID"] > 0;
};
$displayoutput = function($value) {
$this->DisplayTheOutput($value);
};
$collection = collect($this->tables);
$filtered = $collection
->filter($showGreaterThanZero)
->pluck("Table")
->each($displayoutput);
@mlantz
Copy link

mlantz commented Jul 3, 2016

You could also just create that function in a helper somewhere or.... put it in a class which is accessible like a helper class or something:
Then you could do:

function showGreaterThenZero () {}

or

->filter(call_user_func(['classname', 'methodname'])

@jackfruh
Copy link
Author

jackfruh commented Jul 3, 2016

The problem I am having is that there seems to be some data passed in, but I don't know what it's called in the context of the pass in.

for example here's an anonymous function:

$collection->filter(function($inbound) {
  return $inbound > 0;
});

If I want to replace the anonymous function with one I define in my class:

function take1($input) {
  return $input >0;
}

Then when I call it in the context of the collection object i don't know what to pass in:

$collection->filter($this->take1($WhatVariableIsUsedHere))

@mlantz
Copy link

mlantz commented Jul 3, 2016

The filter is always a $value, $key I believe

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment