4

I recently started learning PHP and since I'm used to strongly typed languages (C++, Java) I would really prefer to make use of type hinting and return type declarations. However when I'm trying to use return type declaration for primitives I get a fatal error, stating that my function does not return the correct type.

Here is a code example:

<?php
namespace Foo;

class Bar {

    public function bar() : boolean {
        return true;
    }

}

$bar = new Bar();
$bar->bar();

?>

This will cause a fatal error, stating that Bar::bar does not return a value of Foo\boolean type. So I tried resorting to the global namespace by changing the function prototype to:

public function bar() : \boolean

But then I got a fatal error stating that my function does not return a value of type boolean. I guess PHP is looking for a type called boolean in the global namespace and not for the primitive type. Great, so how am I supposed to indicate that I want my function to return a value of the primitive type boolean?

2
  • 1
    The type is bool not boolean. Commented Feb 19, 2017 at 10:54
  • 1
    You should also put declare(strict_types=1); as the first line of each file. Commented Feb 19, 2017 at 10:59

1 Answer 1

8

The type hint for a Boolean value is actually bool. Try this:

<?php
namespace Foo;

class Bar {
    public function bar() : bool {
        return true;
    }
}

$bar = new Bar();
$bar->bar();
Sign up to request clarification or add additional context in comments.

2 Comments

Damn, I feel stupid. Thank you for the clarification :)
Nah, it's not stupid :) PHP allows classes to start with a lower-case letter, and until it started checking scalar type hints it was very common to see bool type-hinted as boolean (in comments). This is another case of a gotcha where the tooling can do little to help you spot an error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.