1

I am using type declarations in PHP 8.0.7 with a simple class like:

<?php
    class KV {
        public function __construct(private array $storage = []) {}

        public function put(string $key, string $value): bool {
            $this->storage[$key] = $value;
            echo "successfully put {$key} => {$value}" . PHP_EOL;
            return true;
        }

        public function getStorage(): array {
            return $this->storage;
        }
    }

    $kv = new KV();
    $kv->put('foo', 12);    // works
    $kv->put('bar', 123.2); // works
    $kv->put('car', true);  // works

    print_r($kv->getStorage());

However, to my surprise when I try to invoke $kv->put('foo', 12); this does not error with invalid argument type. It should, as 12 is not a string right? What am I missing here? There is explicitly a type declaration in PHP for int, float, bool, object, array, and mixed among others.

Justin
  • 42,716
  • 77
  • 201
  • 296

2 Answers2

3

From the PHP manual:

Strict typing

By default, PHP will coerce values of the wrong type into the expected scalar type declaration if possible. For example, a function that is given an int for a parameter that expects a string will get a variable of type string.

Add declare(strict_types=1); at the top of your script to enforce strict typing.

Siguza
  • 21,155
  • 6
  • 52
  • 89
0

In order to enforce strict type checking, it seems we must use a special syntax in the opening php tag of <?php declare(strict_types=1);

This is silly in my opinion, and strict type checking should be the default especially in PHP 8+.

Justin
  • 42,716
  • 77
  • 201
  • 296