PHP 7 - Why does a method that returns the primitive type String, does not generate error when returning a Boolean value?

8

PHP 7 - Why does a method that returns the String primitive does not generate an error returning a Boolean value?

<?php

class Foo
{
    public function bar() : string
    {
        return true;
    }
}

$Foo = new Foo();
echo $Foo->bar();

?>

Output: 1

link

    
asked by anonymous 08.08.2018 / 18:42

1 answer

8

By default all code in PHP has Weak check, and to enable place a line at the top of the file including before the namespace check the types strictly (check Strong ): ( declare(strict_types = 1); ):

<?php

    declare(strict_types = 1); // habilitando checagem forte

    class Foo
    {
        public function bar(): string
        {
            return true;
        }
    }

    $Foo = new Foo();
    echo ($Foo->bar());


?>

there it generates erro :

  

Return value of Foo::bar() must be of the type string, boolean returned

OnLine Example

References:

08.08.2018 / 19:00