Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer. You can expect quick tips, links to interesting tutorials, opinions and packages. Want to learn the cool stuff? Then sign up now!

Add syntactic sugar by preprocessing PHP

In an awesome article at Sitepoint Christopher Pitt explains how he used the yay macro library to build up plugin framework to add new language features to PHP.

Chris made plugins that allows this syntax in PHP.

// short closure syntax
$items = ["one", "two", "three"];
$ignore = "two";

array_filter($items, ($item) => {
    return $item !== $ignore;
});
//class accessors

class Sprocket
{
    private $type {
        get {
            return $this->type;
        }

        set {
            $this->type = $value;
        }

        unset {
            $this->type = "type has been unset";
        }
    }
}

As with all things, this can be abused. Macros are no exception. This code is definitely not production-ready, though it is conceptually cool.

Please don’t be that person who comments about how bad you think the use of this code would be. I’m not actually recommending you use this code, in this form.

Having said that, perhaps you think it’s a cool idea. Can you think of other language features you’d like PHP to get? Maybe you can use the class accessors repository as an example to get you started. Maybe you want to use the plugin repository to automate things, to the point where you can see if your idea has any teeth.

https://www.sitepoint.com/how-to-make-modern-php-more-modern-with-preprocessing/

Check out some more examples on preprocess.io

Very cool stuff.

Freek Van der Herten is a partner and developer at Spatie, an Antwerp based company that specializes in creating web apps with Laravel. After hours he writes about modern PHP and Laravel on this blog. When not coding he’s probably rehearsing with his kraut rock band. He loves waffles and butterflies.