• Home
  • blog
  • Fun and Functional Programming in PHP with Macros

Fun and Functional Programming in PHP with Macros

I was so excited about my previous article about PHP macros, that I thought it would be fun for us to explore the intersection of macros and functional programming.

PHP is already full of functions, with object oriented patterns emerging relatively late in its life. Still, PHP’s functions can be cumbersome, especially when combined with variable scope rules…

Assembling lego blocks

Consider the following ES6 (JavaScript) code:

let languages = [
    {"name": "JavaScript"},
    {"name": "PHP"},
    {"name": "Ruby"},

const prefix = "language: ";

        language => prefix +

In this example, we see languages defined as a list of programming languages. Each programming language is combined with a constant prefix and the resulting array is logged to the console.

This is about as much JavaScript as we’re going to see. If you’d like to learn more ES6, check out the documentation for BabelJS.

Compare this to similar PHP code:

$languages = [
    ["name" => "JavaScript"],
    ["name" => "PHP"],
    ["name" => "Ruby"],

$prefix = "language: ";

    array_map(function($language) use ($prefix) {
        return $prefix . $language;
    }, $languages);

It’s not significantly more code, but it isn’t as clear or idiomatic as the JavaScript alternative. I often miss JavaScript’s expressive, functional syntax, when I’m building PHP things. I want to try and win back some of that expressive syntax!

Continue reading %Fun and Functional Programming in PHP with Macros%