Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Return value declaration in namespaces

Tags:

php

php-7

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?

like image 423
Krisztián Szabó Avatar asked Feb 06 '23 01:02

Krisztián Szabó


1 Answers

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();
like image 89
Richard Turner Avatar answered Feb 07 '23 19:02

Richard Turner