PHP Macros for Fun and Profit!

I was originally going to call this “Micro Macros with Márcio Perfectly Pragmatic Pre-Processor library”, but I didn’t think Bruno would approve…

I get really excited when developers feel empowered to create new tools, and even new languages with which to solve their problems.


You see, many developers come to PHP from other languages. And many PHP developers can code in more than one language. Often there are things in those languages — small syntax sugars — that we appreciate and even miss when we’re building PHP things.

Complex laboratory labyrinth

Adding these to a language, at a compiler level, is hard (or is it?). That is unless you built the compiler and/or know how they work. We’re not going to do anything that technical, but we’re still going to be empowered.

When I used to write Ruby (or languages similar in this regard), I used to use list index ranges. They look something like this:

few = many[1..3]

We can expect code like that to take the second, third and fourth item of the many list, and assign them to the few variable. We can do something similar, using array_slice:

$few = array_slice($many, 1, 3);

I think the Ruby equivalent is far more elegant. We can also use variables and negative values for the lower and upper bounds of the range. It’s brilliant!

Getting Started with Macros

Inspired by a recent SitePoint post, I decided to try and add this syntax to my applications. The trouble is I don’t understand the PHP interpreter well enough to be able to add it. Then I remembered Márcio Almada’s Yay library. It adds macros through pre-processing. Here’s an example of something simple you can do with it:

macro {
    unless (···condition) { ···body }
} >> {
    if (!(···condition)) { ···body }

$condition = false;

unless ($condition) {
    print "look ma! macros...";

That example is straight out the readme (with a few style differences).

Continue reading %PHP Macros for Fun and Profit!%