PHP is weird, but it can be cool at times!

Here are some strangely cool features from PHP that can make your life easier 🙂

This article is also available on Medium.

PHP is weird.

It’s a bit like Java: people keep on saying it’s going to die but, nevertheless, it’s still powering more than half the websites on the planet (partly because it’s the language of WordPress which is, today, the most used CMS in the world). Basically, it’s been there for so long that it’s taken its place… and even critics that point the flaws and weirdness of these languages can’t shake things enough to reverse the trend.

Big companies like Facebook or Wikipedia use it, too, which cements this language as a fundamental building block of the web ecosystem. But, in truth, you kind of feel it’s more of a burden than an actual choice; according to this interview of Yishan Wong, engineer at Facebook, from a few years ago:

The reason Facebook hasn’t migrated away from PHP is because it has incumbent inertia (it’s what’s there) and Facebook’s engineers have managed to work around many of its flaws through a combination of patches at all levels of the stack and excellent internal discipline via code convention and style. […]

And I think that’s the main thing with PHP: it requires an amazing amount of rigour and vision to get a decent structure. Otherwise, it is so lenient and permissive that you can quickly make a real mess. The language has grown over the years and, now, by mixing up imports and classes, you can cut down your code in readable chunks. Still: you always end up concatenating and parsing strings a thousand times, using numbers as characters and vice-versa, or storing your items in arrays that were actually keyed like dictionaries…

But! This is also something that lets you do amazing stuff quite quickly

So here are a few examples of strangely cool features of PHP 😉

Creating enums and listing the possible values

If you use a PHP version that is lower than 8.1, then you can’t actually create enums in PHP: this feature is not available in the language. And remember that PHP’s hegemony is half due to legacy, so chances are that you will be on an older version.

However, just like I discussed in my last Python tutorial, you can sneak pass this difficulty and use classes in place of actual enumerations.

For example, let’s say you want to get an enumeration for string case manipulations. Then you could do something like this:

Making the class abstract (with the abstract keyword) is a way to insure that you can’t actually instantiating this class: it’s a way to force it to be pure data. Making the variables constants (with the const keyword) is really handy because it means we’ll be able to access the values without creating an instance of the StringCasing class:

Of course, you can assign the values to whatever is more intuitive: here, we could use strings instead of ints, for example, if we want to store those values in config files but still get readable outputs:

And if you want to list all possible values for your enum (suppose you want to have a dropdown HTML element to choose one of the available casings), you can use reflection. I’ve talked about it many times in my C# articles and my RTS tutorial: reflection is about “discovering” info on your objects at runtime, rather than hardcoding types and classes. So, here, it allows us to dynamically get the list of values, just by getting the class constants:

Once again, we’re using a static function so that we can call this method without instantiating the StringCasing class 🙂

If you want something more powerful, this Stack Overflow answer gives a really nice example of a boosted enum class that can be extended, that lets you list the possible values and that allows you to check if a key or a value is allowed. This code also optimises the reflection part by caching the results because this can lead to overheads if it’s used too often.

Note: the really cool thing is that the new enum feature introduced in PHP 8.1 works seamlessly with this technique: apart from the definition of the enum itself, you can leave the rest of your code as-is because the new enums also use the double colon :: accessor.

Calling a class or a function by name

To continue on the topic of classes, methods and reflection: PHP is peculiarly easy-to-use when it comes to calling classes or methods dynamically, meaning that you have the name of your class or function in a variable and you want to get back the “real” matching object.

In C#, you’d have to use the System.Reflection package to extract back the class from the current assembly; in Python, you’d have to import the proper module and then get the corresponding attribute in it, or use the importlib, as explained here; in JavaScript, you’d have to access some global context manager, like window, and get the function from it – but then, on Node, it would be different…

In PHP, calling a class or a method by name is just about having a name, and calling it 🙂

Like this:

It sounds a bit too simple, even!

Of course it works the same way with classes and you can pass in parameters, just like in a normal call:

So, yes, in truth you have to make sure that the class or function is indeed defined, so this might require a few additional imports and references if your codebase is properly split up, but I find it pretty surprising how straight-forward it is, thanks to PHP’s core idea of templating and concatenating everything 😉

Some array utilities

In my opinion, working with arrays in PHP is inevitable but can be tiring, namely because the language has a tendency to “mix up” the keyed and non-keyed arrays. Meaning that you use the same container both for ordered lists (with numerical indices) and key-pair values… that are called dictionaries in many other programming languages!

It can make it hard to know whether the object you’re currently manipulating is just a suite of values, or if there are also keys associated with them. Also, from PHP 5.4.0, non-keyed arrays can actually be written using the [] shortened syntax, which means that you have up to three ways of writing arrays…

But in spite of all these flaws (to my eyes, at least), PHP also has some neat features for these arrays, such as:

  • getting a count of all the elements in a list:
  • shuffling all the elements in the array:
  • getting one or more random items from the array:

Now, of course, there are way more array functions to dive in like remapping, filtering, recursive walking, etc.

But those examples are interesting because other programming languages can make these computations (somewhat overly) complex. For example, getting the element count of an array in Python requires you to import the collections built-in module and create a Counter; and, in C#, shuffling or extracting random elements is done using a random generator!

That’s one of these strange cases where PHP actually shines by its simplicity 😉

Bonus: creating a singleton

This is not a special or unique feature per se, but it’s sometimes useful to know how to create singletons in a programming language that follows the OOP paradigm.

As explained by Bob Nystrom in his amazing book “Game Programming Patterns” (available for free on the web), singletons can be dangerous and they’re not always a good idea. But when you clearly design your application and you want to easily access an instance that can only be created once, this pattern can be interesting.

For example, perhaps your application has a global instance that contains the current config; to make it a singleton, you have to use a static variable; then, whenever you access your instance, if the variable is null, you fill it, else you return it directly:


I still think that PHP is strange and oftentimes prone to lots of errors because of how permissive it is; but using it more, and in particular diving into more recent features, shows me that this language can do some really nice stuff and that can you get back control, with enough discipline…

… and since I’m pretty sure PHP is deeply nested into the net and will not disappear any time soon, I guess we may as well learnt those little tricks and make our lives easier 🙂

What about you: do you use PHP, or are you avoiding it at all costs? Do you use recent versions, or is it about polyfilling new features on old systems? Feel free to react in the comments!

Leave a Reply

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