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 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:
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 gem
s, 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
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.';
});
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, DateTime
s.) 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.
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.