PHP object functionName():bool

1.1k views Asked by At

I've one PHP class, in that I found one a function e.g

public static function success(string $userid, string $message):bool
{
    return self::add($userid, $message, 'success');
}

Can someone please tell that what does mean :bool after function name?

5

There are 5 answers

0
Matt S On

From the documentation (emphasis mine):

PHP 7 adds support for return type declarations. Similarly to argument type declarations, return type declarations specify the type of the value that will be returned from a function. The same types are available for return type declarations as are available for argument type declarations.

Strict typing also has an effect on return type declarations. In the default weak mode, returned values will be coerced to the correct type if they are not already of that type. In strong mode, the returned value must be of the correct type, otherwise a TypeError will be thrown.

0
Script47 On

:bool is forcing the return type of the function, in your case it is a boolean.

<?php

function arraysSum(array ...$arrays): array
{
    return array_map(function(array $array): int {
        return array_sum($array);
    }, $arrays);
}

print_r(arraysSum([1,2,3], [4,5,6], [7,8,9]));

PHP 7 adds support for return type declarations. Similarly to argument type declarations, return type declarations specify the type of the value that will be returned from a function. The same types are available for return type declarations as are available for argument type declarations.

Strict typing also has an effect on return type declarations. In the default weak mode, returned values will be coerced to the correct type if they are not already of that type. In strong mode, the returned value must be of the correct type, otherwise a TypeError will be thrown.

Note: When overriding a parent method, the child's method must match any return type declaration on the parent. If the parent doesn't define a return type, then the child method may do so.

A full list of new features can be found here.

0
Hatted Rooster On

It explicitly states that the function success will return a bool and only a bool, thus preventing unintended return values by implicit casts etc.

0
Pubudu Jayawardana On

Simply, it is the indicator of the value type the function will output. This is introduced in PHP 7. If you try to output other than a bool value, there will be an error.

0
cherrysoft On

It will force the return value of your method to be a boolean.

e.g. if your self::add method returns a string the result will be 1 for true.