Search code examples
phpstrong-typing

PHP: Declaring a "numeric" type


With modern versions of PHP, we can declare many different types, union types or even mixed. However, I work with Magento 2, and its often impossible to know if you're going to get an ID of 7 or '7' passed to your method

My goal is to validate, using type declaration if possible, whether the input value can be successfully converted to or is already an integer. Because MySQL WHERE conditions treat integers and strings containing only numbers identically, many LAMP applications aren't strict about passing ints vs strings to methods that deal with IDs. However, if I simply declare a union type of int|string, then it would accept the value "example" which isn't numeric and would error once it got to MySQL. So, I can't find a way to validate the input in the declaration.

Is there a clean way to declare a numeric type if I can't control what's sent to my method?


Solution

  • You can just declare int as the type of a function's input parameter and PHP will automatically accept a stringified integer (e.g. '7') and coerce it into an int, but trying to pass in any other string will cause an exception.

    Example:

    function foo(int $bar) { 
     var_dump($bar); 
    }
    
    echo "These ones are all ok:".PHP_EOL;
    foo(7);
    foo('7');
    foo("7345");
    
    echo PHP_EOL."And now for a bad one...".PHP_EOL;
    foo("sgjhdfkg");
    

    Outputs:

    These ones are all ok:

    int(7)

    int(7)

    int(7345)

    And now for a bad one...

    Fatal error: Uncaught TypeError: foo(): Argument #1 ($bar) must be of type int, string given

    Live demo: https://3v4l.org/LnQvW