Link Link -4 years ago 149
PHP Question

PHP strict types - weird boolean behavior

i have this code:



# 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. 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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download