• Skip to primary navigation
  • Skip to main content
Sal Ferrarello
  • About Sal Ferrarello
  • Speaking
  • Connect
    Mastodon GitHub Twitter (inactive)
You are here: Home / Draft / PHP declare(strict_types=1);

PHP declare(strict_types=1);

Last updated on October 23, 2019 by Sal Ferrarello

What does declare(strict_types=1); do in PHP?

PHP is a weakly typed language, which means that when a value is of the wrong type, PHP tries to cast it to the proper type.

For example if you try to add an integer and a string,

echo 5 + "3";

PHP will try to cast the string ("3") to an integer (3) and use that value, so our result is 8.

Weakly Typed Type Hints

When we type hint a function argument, PHP will do this same casting.

Type Hint Casting

Here our function is expecting an integer but instead we pass it a string ("3").

This is okay because, PHP casts our string ("3") to an integer (3) and uses that value.

function outputAnInteger(int $num)
{
    echo $num;
}
outputAnInteger("3");

Our output is 3.

Strict Type Hints

By adding the line

declare(strict_types=1);

to the beginning of the file, function calls will respect type hints strictly (they will not be cast to another type).

declare(strict_types=1);

function outputAnInteger(int $num)
{
    echo $num;
}
outputAnInteger("3");

This code results in

Fatal error: Uncaught TypeError: Argument 1 passed to outputAnInteger() must be of the type int, string given

Where to declare strict_types

The declare(strict_types=1); is applied to all function calls being made in the file where it is declared.

In other words, if I declare my function in a file called functions.php

function outputAnInteger(int $num)
{
    echo $num;
}

and I make the loosely typed call outputAnInteger("3"); from a file called mylogic.php

  • mylogic.php adding declare(strict_types=1); would cause a Fatal PHP error
  • functions.php adding declare(strict_types=1); would have no effect on the outputAnInteger("3"); call (which appears in mylogic.php)
Sal Ferrarello
Sal Ferrarello (@salcode)
Sal is a PHP developer with a focus on the WordPress platform. He is a conference speaker with a background including Piano Player, Radio DJ, Magician/Juggler, Beach Photographer, and High School Math Teacher. Sal can be found professionally at WebDevStudios, where he works as a senior backend engineer.

Share this post:

Share on TwitterShare on FacebookShare on LinkedInShare on EmailShare on Reddit
Warning! This is a draft, not a finalized post. See full draft disclosure.

Filed Under: Computing, Draft, Programming Tagged With: PHP

Reader Interactions

Leave a Reply Cancel reply

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

Copyright © 2023 · Bootstrap4 Genesis on Genesis Framework · WordPress · Log in