Cool New PHP 7 Features for WordPress Developers

PHP has changed a lot in the last few years. And even before that, it had changed a lot. In short, modern PHP is a great and cool language, with only a few of the worst problems that people who last used it a decade age will remember. (Modern) PHP 7 and WordPress haven’t really gone together historically.

But soon we can use all this in WordPress. In WordPress 5.2, WordPress will stop targeting working with PHP below 5.6. By the end of the year, WordPress plans to be on PHP 7.0. It’s not the absolute latest and greatest, but it shows a new commitment to make the best of PHP available to all WordPress developers. So that’s our focus today: (modern) PHP 7 WordPress code, and some of the cool things we can do with it.

But the gap between the PHP we’ve always had (to encourage you to write) for WordPress and modern PHP is big. In this article I’ll blaze through the highlight features that’ll make developing for WordPress in a PHP 7 world great. Surely most of the techniques that one used for being a good PHP+WordPress developer for while are still good to know. But surely some of them are due for an upgrade this year.

What I mean by “modern PHP,” and how it differs from WordPress

As I write this, PHP 7.3 is the “modern” version. And WordPress PHP for a while has maintained compatibility with PHP 5.2. While the number of versions between 5.2 and 7.3 may be fewer than a WordPress developer would guess (i.e, it wasn’t the approximately 20 it kind of looks like), it is a lot. And a lot changed. So here we’re going to be confined to strict summaries of core features that are interesting and better since PHP 5.2. Please, if I forgot your favorite leave me a comment. 🙂

Syntactical Niceties: PHP has Short Array Syntax! Etc

This will just be a sequence of small changes in your syntax that PHP 7 WordPress code will allow. Where I can recall, I’ll give a bit of history and bit of summary. But as I said this is a lot of ground that comes from WordPress PHP 7 compatibility, so I’ll move quick and just touch on all the topics.

PHP Short Array Syntax

This one’s quick: in PHP 5.4, we got full-fledged support for shorter array syntax. Be gone, function-looking array declarations. And welcome your square brackets. So array(1) is really just [1]. What’s not to like? In other words, we have this available always and everywhere:

$args = ['posts_per_page' => 7];

Pretty cool.

Null-Coalesce Operator

This ones a little more nerdy and complex. Because we’re in a hurry, we’ll assume you have some familiarity with ternary operators. I wrote an article about them if you’re not familiar.

Now, what does this do? What it does is let us bypass a necessary isset call in legacy PHP. So historically PHP would error if you assumed a value (most often in an array) existed and it didn’t. Now using the ?? operator, you don’t have to worry. Code sample:

$x = ["yarr" => "meaningful_value"];
var_dump($x["aharr"] ?? $x["waharr"] ?? $x["yarr"]); // string(16) "meaningful_value"

Spaceship Operator

This one mostly I mention because it’s got a fun name. What’s PHP’s spaceship operator? It’s this: <=>. This is really a shorthand functionality that’s useful in just a small number of cases, but for things like usort, you used to have to make longer expression often with a ternary operator. Now you can do simpler things. Relevant sample code:

// Sort $things by 'foo' property, ascending
usort($things, function ($a, $b) {
    return $a['foo'] <=> $b['foo'];
});

OOP-ish Niceties You Should Consider (from PHP 5.x)

WordPress itself, and WordPress development generally, isn’t super object-oriented. There are objects around, but I’d say more than half of the WordPress code I regularly see isn’t object-oriented. Most of these features will only make sense if you’re a little familiar with OOP. If you’re not, we’ve got a great free course to help you come up to speed on OOPHP.

PHP Namespaces are Useful!

This one I’ve written up at length here at Thoughtful Code. So I’ll keep this one short and sweet. Namespaces let us keep like things together through a method other than shoving them into an object. We have “virtual folders” called “namespaces”, so that I may have something like RequireFeaturedImage\Utility as a place that I then throw a couple different classes or functions. It’s pretty powerful.

If you want to understand PHP namespaces in more depth, I already wrote that:

A Complete Guide to PHP Namespaces

Composer Comes from PHP Namespaces! And can change your life!

So this is a rabbit-hole far too deep to explain in depth right now. But Composer (which really needs PHP namespaces to work well) is the dependency manager that PHP has needed for about about 10 years, and has had for about 5. But Composer and WordPress haven’t been great friends, in part because WordPress has focused on PHP 5.2 compatibility, which Composer could never do.

If you’re still not understanding this, some analogies that may help you. Composer is like npm in the JavaScript ecosystem, Ruby’s gems, or you phone or computer’s App Store. And it’s totally free! It’s certainly something you must at least vaguely understand to be a modern PHP developer for WordPress.

PHP Traits are Great! (Sometimes)

Traits are, essentially, small bits of functionality you can “mixin” to a class. I chose to focus on them over other common PHP features that PHP got since 5.2 (like interfaces, etc) that WordPress developers haven’t used as they’re kind of novel.

I have mixed feelings about traits, which are a useful way to modularize code, but also a great way to confuse the next developer who missed your little use statement inside of a class definition. On the whole though, they’re a very useful tool to understand.

A code sample doesn’t quite do it justice. But here’s the briefest one that might make sense:

trait SayHelloWorld {
    public function sayHello() {
        echo 'Hello World!';
    }
}

class MyHelloWorld extends Base {
    use SayHelloWorld;
}
$hello = new MyHelloWorld;
$hello->sayHello() // 'Hello World!'

The core this to notice about code sample MyHelloWorld never had the method sayHello in its declaration. It got it from using the SayHelloWorld trait.

Get Full Names with ::class Easily

In PHP 5.5, it became possible to use ClassName::class to get a fully qualified name of class ClassName. That is, ClassName::class, will give me '\App\Utilities\Classname' which can be invoked elsewhere in my code, or loaded up in some other way. This is mostly useful and necessary because of namespaces. This is such a simple little trick, but I use it all the time, so I just had to mention it.

Anonymous Functions are great for Quick WordPress Hooks

This one isn’t very OOP, but for years I’ve been explaining WordPress hooks with function names. But for nearly a decade, you’ve been able to use anonymous functions in PHP and WordPress. But with support for 5.2 (which didn’t support it) finally going away, you’ll be able to do this in places for quick and convenient hooking. (There are still lots of reasons not to, but that’s a whole other discussion):

add_action('init', function() {
    echo 'WPShout was here with an anonymous function.';
});

Types! So much Types (WordPress Developer features from PHP 7 and up)

Throughout PHP 5, you had support for some very basic type declaration. What I mean is that you’d see things like this from time to time:

function my_adder(MyNumberClass $first, MyNumberClass $second) {
    return $first->add($second);
}

This is a silly example, but you get the idea. These declarations inside the parameter of my function of classes that my function works with would tell other developers what they should pass in to make it work. But throughout PHP 5.x, you were limited to a few types: classes, arrays, and callables (functions, including anonymous ones, and some classes).

As I said, declaring types helps people realize how you expect your code to interact with them. But you can take the things you’re able to declare types for much further. For example, you can tell people what you return, and you can specify more than classes that you’ll accept. That gets to our first two PHP 7 WordPress features to understand.

Return type declarations

In PHP 7 and above, you’ll sometimes see a pretty weird function signature:

function foo($time_string): DateTime { 
    return new DateTime($time_string);
}

So, what’s all that : DateTime stuff? It’s telling you that the function foo will pass you an instance of the DateTime class. (The DateTime object is baked into PHP, and is used to represent, well, DateTimes.) This lets me tell the things that will call my function (or class method, etc) what they should expect.

Return types are also nullable (may sometimes return a null instead of the type they specify), which you might expect from the way it’s declared: foo(): ?DateTime is a function that will either return null or a DateTime object.

Scalar Type Hints are Now Available

Upgrading our weird function from the last time, we can now also do “scalar” type hints in PHP. So we’d have:

function foo(string $time_string): DateTime { 
    return new DateTime($time_string);
}

As I mentioned above, in PHP 5 you couldn’t specify anything but classes, array and callable as parameter types. In PHP 7, we’re able to also specify scalar types, like integer, string, etc. (For a fuller understanding a scalar types in PHP, read this article.)

Sidenote: You Can REQUIRE The Use of Types

In one of my favorite legitimate weirdnesses about PHP, you can declare that you want to require that all functions declare the types of their parameters and their returns. But you do it in a way that uses some “type juggling.” To use the feature, you’ll add at the top of a .php file (inside of <?php tags), the following:

declare(strict_types = 1);

I think this is good practice, if you’re trying to use strongly typed PHP code. But I also just think it’s a funny reality that you’re using an integer to set a boolean. 🙃

Oh Yah! Anonymous Classes in PHP

Like in the PHP 5 series, which was mostly focused on OOP, I’ve got to throw in a useful little random thing. Specifically, in PHP 7, you’re able to make an anonymous class. As you’d likely guess, this is pretty similar to the anonymous functions which was my bonus there. So you can now do:

$util->setLogger(new class {
    public function log($msg)
    {
        echo $msg;
    }
});

Anonymous classes have most of the same upsides (super quick), and same downsides (can be hard to find and understand as not-their-author) of anonymous functions. So don’t go overboard with these newfound powers.

PHP 7 WordPress Code Will Be Better

In 2020, we’ll be able to write PHP 7 WordPress code everywhere. It will be glorious. Or more accurately, it’ll be a little better than what we’ve been able to do for that last few years. There’ll still be a lot of WordPress-reality we’re also staring in the face of. But hopefully I’ve shared some of my enthusiasm for these great features finally coming to WordPress that you’re also getting excited. PHP future is awesome! And I’m so glad it’s finally arriving for WordPress. 😊


Add a Comment

Your email address will not be published. Required fields are marked *