PHP7: methods with a scalar type declaration refuse to enter juggle NULL values, even in weak / coercive mode

Since PHP 7.0 , scalar type tips int, float, stringand boolmay be included in the signature method. By default, these type declarations work in weak / coercive mode (or type juggling "). According to the PHP manual :

PHP, if possible, will force values ​​of the wrong type to the expected scalar type. For example, a function that is given an integer for a parameter that expects a string will receive a variable of type string.

But even if you can get NULL at integer 0, a method with a type intwill refuse to force the input value NULLto integer 0.

<?php

class MyClass
{
    public function test(int $arg)
    {
        echo $arg;
    }
}

$obj = new MyClass();
$obj->test('123'); // 123
$obj->test(false); // 0
$obj->test(null);  // TypeError: Argument 1 passed to MyClass::test()
                   // must be of the type integer, null given

And similarly, although you can force NULL to a boolean false, a method with a type boolwill be discarded to force the input value NULLto boolean false. The same goes for hints such as floatand string.

This behavior seems to contradict the documentation on php.net. What's going on here?

+4
source share
1 answer

NULL .

RFC PHP 7:

( ) , PHP. NULL: , , NULL , NULL.

NULL NULL :

<?php

class MyClass
{
    // PHP 7.0+
    public function testA(int $arg = null)
    {
        if (null === $arg) {
            echo 'The argument is NULL!';
        }
    }

    // PHP 7.1+
    // https://wiki.php.net/rfc/nullable_types
    public function testB(?int $arg)
    {
        if (null === $arg) {
            echo 'The argument is NULL!';
        }
    }
}

$obj = new MyClass();
$obj->testA(null); // The argument is NULL!
$obj->testB(null); // The argument is NULL!
+5

Source: https://habr.com/ru/post/1683375/


All Articles