PHP strict_types

Last updated on

If you want to write good PHP code, strict mode should be on your radar. Strict mode—activated by the command declare(strict_types=1); at the top of your PHP script—is more than a minor detail. It is like a rule you set up to make PHP more strict. That is, it prevents PHP from becoming too lax about data types and makes PHP take type declarations seriously.

By the end of this article, you will understand not only why you'd want to use strict mode but also how it works and some quick examples that make the benefits concrete.

Now, let’s take a look at the syntax of PHP strict_types.

What is "strict_types"?

OK, say you're telling PHP to expect an integer. If you do not have a strict mode on and you pass it a string containing some numbers, PHP just rolls with it, quietly converting it into an integer. It sounds convenient, but it's also a certain recipe for disaster.

That is where strict mode kicks in—it tells PHP that if you say integer, that is what you want—an integer and nothing else. Otherwise, it will throw an error. It may be a bit intense at first, but the upside is that it catches errors from the beginning, so you won't have to deal with wacky behavior later on.

How to Enable Strict Mode in PHP

Activating strict mode is fairly straightforward. To enable it, add the following to the absolute top of your PHP file:

<?php
declare(strict_types=1);

// Rest of the PHP code follows...

This should be the very first line of your script. The moment PHP reads this, it's in full strict mode, where it will enforce any data type declarations you use in function parameters, return types, or other places. Note that this works on a per-file basis—if you want to have strict mode for every file, you'll have to put this in each file individually.

So, the strict mode can take a value of either 0 or 1.

The declare Keyword:

The declare keyword in PHP allows for the setting of a number of directives. In terms of strict_types, the declare keyword toggles on or off behaviors related to type checking.

The strict_types=1 Directive:

This declaration, in particular, under the declare statement, if set to 1, enables strict type-checking for the entire script:

<?php
declare(strict_types=1);

For those scenarios where strict type checking is not required, setting it to 0 can disable this feature.

Here is an example:

<?php
declare(strict_types=0);

Strict mode pays off in larger and more intricate projects, where bugs might be nested anywhere. By enforcing stricter rules, it will make it easier to find problems early on, which is much better than discovering them later. If you're writing code that's expected to live a little longer—or if others are working with you—strict mode can save you and your fellow team members a lot of frustrating debugging.

Let’s move into the section below to understand how Scalar Type Declarations work with strict_types.

Scalar Type Declarations with PHP strict_types

One of the key areas where strict_types really shines is with scalar types: integers, floats, strings, and booleans. Scalar-type declarations combined with strict_types fortify your code against insidious type-related bugs.

Here is an example:

<?php
declare(strict_types=1);

function multiply(int $a, float $b): float {
    return $a * $b;
}

// Calling the function with precise scalar types
$result = multiply(5, 2.5);

Here, the multiply function expects an integer $a and a float $b. If you attempt to invoke it with mismatched types, say a string and an integer, strict_types springs into action, throwing a TypeError:

<?php

// Calling the function with mismatched types will result in a TypeError
$result = multiply("5", 2);

It will proactively detect the errors to make sure that your functions receive the appropriate scalar types, thus preventing possible runtime disasters.

So why do we've to use strict mode? let's see the answer below.

Why Strict Mode Is Worth Your Time

With strict mode, PHP may be a little more finicky, but that's the point. It makes you much clearer with your data types, which can save you from a lot of issues down the line. You'll also feel more confident that your code really works exactly as you designed it when you know PHP isn’t going to do any type of conversion.

This practice is especially good for beginner and intermediate PHP developers who want to enhance their skills in writing stable, professional code.

Wrapping Up

That little adjustment with declare(strict_types=1); can make a big difference in your PHP projects. By explicitly declaring how your code works with data, you can avoid pesky bugs and make your code easier to work with as it grows in size. So next time you start a new project in PHP, consider making strict mode part of your toolkit. It might be tough at first, but it's a step toward writing cleaner, more reliable PHP code.

Frequently Asked Questions (FAQs)

  • What is PHP Strict Mode?

    PHP has something called strict mode, which forces strict adherence to data types. Once enabled with declare(strict_types=1);, PHP will only accept the defined data types in function arguments and return values. For instance, if a function is defined to take an integer, PHP will throw an error if you pass it a string, even if that string looks like a number. This prevents accidental type conversions that might lead to unexpected behavior or bugs.
  • How do I turn on strict mode in PHP?

    To enable strict mode in PHP, insert the line declare(strict_types=1); at the top of the PHP file, outside of any namespace or block:
    <?php
    declare(strict_types=1);
    
    This must be the first line of your file for it to work.
  • Why and when should we use "declare(strict_types=1);" in PHP?

    Using declare(strict_types=1); makes PHP stricter with the data types you specify. This leads to cleaner code and more predictable behavior, helping you catch data type errors early and making debugging easier. It’s especially useful in big projects where consistency and reliability are essential.
  • What happens if I don’t use strict mode in PHP?

    PHP is more lenient with data types if strict mode isn’t used. For example, if you define a function to accept an integer but pass a string containing numbers, PHP will silently convert the string to an integer. While this can be convenient, it can also result in type-related bugs hiding in complex applications. Strict mode reduces this risk by enforcing precise data types.
  • Does strict mode apply to all PHP files?

    No, strict mode only applies to the PHP file where you declare it. Each file that needs strict mode must have declare(strict_types=1); at the top. It won’t affect other files in your project unless you put the declaration in those files too.
  • Can I use strict mode with PHP versions prior to PHP 7?

    No, strict mode was introduced in PHP 7. If you’re using a version before PHP 7, declare(strict_types=1); won’t work. For PHP 7 and newer, strict mode is fully supported and encouraged where strict data type control is beneficial.
  • What is the difference between strict mode and type hinting?

    Type hinting in PHP allows you to specify what data types a function should accept and return, helping PHP understand the types you expect. However, without strict mode, PHP will still perform type conversions. With strict mode declare(strict_types=1);, PHP enforces those data types strictly, throwing errors for mismatches instead of silently converting types.
  • Does strict mode affect performance in PHP?

    Strict mode itself doesn’t significantly impact performance. It may slightly increase development time since developers need to be precise with data types, but this initial effort often saves time in debugging and improves code stability over a project’s lifespan.
  • Can I disable strict mode for portions of a PHP file?

    No, once declare(strict_types=1); is defined at the top of a PHP file, all code within that file is subject to it. To disable strict mode, you would need to remove the declaration or use a different file without it.
Share on: