Functional PHP

Reading this article got me to thinking…

Since PHP also has closures this should be doable in it as well.

$wordHasChar = function($word, $char) { 
  return stripos($word, $char) !== FALSE;
};

$wordStartsWithChar = function($word, $char) {
  return stripos($word, $char) === 0;
}

$findWords = function( $char, $string, $condition ) {
  return array_filter(explode(' ', $string), function($e) use ($char, $condition) {
    return $condition($e, $char);
  } );
};

Granted, the above is rather contrived and there are better ways to go about the process given. The idea of passing a function as an argument in PHP hadn’t occurred to me despite the fact I do it all the time in Javascript. I think a major limiting factor is going to be PHP’s need of the use statement in closures, but I could be wrong. Anyway, continuing the above, if you wanted all members of a db return array containing a letter A starting a word…

$char = 'A';
$hasA = array_filter($data, function($e) use ($char, $findWords, $wordStartsWithChar) {
  return $findWords($char, $e, $wordStartsWith);
});

On one hand it feels like it could be nifty. On the other, bizarre. Thoughts?

EDIT: None of the above code tested - I’m just musing out some thoughts.

2 Likes

It might be my level of experience, but I find code like that hard to understand. I find Javascript often hard to read too, when it is written like that. So, readability is, to me, an issue with that kind of functional programming. Other than that, it is intriguing.

Scott

1 Like

With the given example (using arrays) I see the main problem in the inability to chain the callbacks with array functions (it could be done but then it creates quite the messy code). (although I did write something to address that …)

And another lesser problem is that not every traversable structure supports array functions. (think of e.g. FileSystemIterator where you would filter file names. right now there is an explicit FilterIterator for that purpose)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.