0

i have this code:

<?php

    declare(strict_types=1);

    # test_1 with bool
    function test_1(bool $bool) {
        return $bool ? 'Yes' : 'No';
    }

    # test_2 with boolean
    function test_2(boolean $bool) {
        return $bool ? 'Yes' : 'No';
    }

    $value = false;

    # Why does this work ...
    echo test_1($value) . "<br>";

    # ... but this doesn't?
    echo test_2($value) . "<br>";


?>

Strict types seem to work with bool but not with boolean.

php.net says:

Aliases for the above scalar types are not supported. Instead, they are treated as class or interface names. For example, using boolean as a parameter or return type will require an argument or return value that is an instanceof the class or interface boolean, rather than of type bool

But somehow i don't get it. Can anyone explain that to me please?

2 Answers2

1

PHP supports only int, float, bool, string and array types. Any of different return type (like boolean) references to class name.

<?php declare(strict_types=1)

class boolean {}

func testReturnBoolean(): boolean {
    // this function should return instance of
    // class "boolean", not bool type (true/false)
}

func testReturnBool(): bool {
    // this function should return true or false,
    // otherwise it throws an exception
}

func testReturnBoolOrNull():? bool {
    // this function should return true, false or null
    // otherwise it throws an exception
    // syntax :? string works since php 7.1
}

More about function arguments and return type declarations.

Grzegorz Gajda
  • 2,424
  • 2
  • 15
  • 23
0

PHP doesn't allow you to use boolean for the type definition, because the keyword is bool. If you type boolean, it will interprete it as a call to a class name. What is hard to understand?

junkfoodjunkie
  • 3,168
  • 1
  • 19
  • 33