Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

SitePoint PHP Blog:
Fun and Functional Programming in PHP with Macros
Apr 04, 2016 @ 10:13:37

The SitePoint PHP blog has a new tutorial posted from author Christopher Pitt continuing on his look at macros in PHP (part one is here). In this new tutorial he gets beyond the basic example he provided in part one and recreate some expressive syntax from Javascript and prefixing strings.

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…

[...] It’s not significantly more code [to append the prefix in PHP vs Javascript], 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!

He starts with a quick install of the yay library used in the first part of the series. Instead of the manual prefixing from his first example, he creates a macro that uses the array_map handling to generate the necessary code once the pre-compiler has done its job. He then expands on this simpler solution and updates it to allow for the setting of the prefix string. It gets a little complex but he walks through each step of the way, explaining the code that's added and what it expands out to. The result is a map method that generates a bit of code that's eval-ed to handle the prefixing automatically.

tagged: macro series part2 tutorial array map prefix advanced precompile yay library

Link: http://www.sitepoint.com/functional-programming-in-php-with-macros/

Trending Topics: