1

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 Answers 5

1

: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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

0

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.

Comments

0

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.

Comments

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.