Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Null and false can be used as stand-alone types in PHP 8.2

The latest version of PHP, PHP 8.1, has been around for quite some time and it comes packed with some great new features and enhancements.

After the release of PHP 8.1, the next release that developers are keeping their eyes on is PHP 8.2 and it has got some interesting RFCs accepted recently.

One of them is the possibility to use null and false as stand-alone type declarations, wherever type declarations are currently allowed in the language.

How?

From PHP 8.2, if you think some class method would always return null, you can type-hint it using null like so.

The same goes for variables as well.

class Nil
{
    public null $nil = null;
 
    public function isNull(null $nil): null 
    { 
        /* ... */ 
    }
}

Similarly, you’d be able to type-hint methods and variables using false as well.

class Falsy
{
    public false $falsyVaribale = false;
 
    public function isFalse(false $falsyVaribale): false 
    { 
        /* ... */ 
    }
}

Why?

The primary motivation behind implementing this according to the RFC is the language authors want to make the type system complete by adding the ability to type the unit type (null and false).

This is to make it inline with the new features that is been added recently like the support for the top type mixed in PHP 8.0, the bottom type never in PHP 8.1, and support for composite types in PHP 8.0 with union types, and 8.1 with intersection types.

Gotcha

One thing to keep in mind when type-hinting method and variables using null and false is, if you try to mark null as nullable (?null), it will result n a compile-time error which is in line with PHP’s current type resolving redundancy rules.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?