Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: bool vs boolean type hinting

I've been trying to use type hinting more in PHP. Today I was writing a function that takes a boolean with a default parameter and I noticed that a function of the form

function foo(boolean $bar = false) {     var_dump($bar); } 

actually throws a fatal error:

Default value for parameters with a class type hint can only be NULL

While a function of the similar form

function foo(bool $bar = false) {     var_dump($bar); } 

does not. However, both

var_dump((bool) $bar); var_dump((boolean) $bar); 

give the exact same output

:boolean false

Why is this? Is this similar to the wrapper classes in Java?

like image 351
Jimmy P Avatar asked May 16 '17 18:05

Jimmy P


People also ask

What is type hinting in PHP?

Type hinting is a concept that provides hints to function for the expected data type of arguments. For example, If we want to add an integer while writing the add function, we had mentioned the data type (integer in this case) of the parameter.

What is a bool in PHP?

PHP Booleans A Boolean is a variable that can have one of two possible values, true or false. Boolean is the simplest data type in PHP. It holds either true or false. To specify a boolean, you can use constants true and false (Both are case-insensitive).

How can check boolean value in if condition in PHP?

The is_bool() function checks whether a variable is a boolean or not. This function returns true (1) if the variable is a boolean, otherwise it returns false/nothing.

When was type hinting added PHP?

In May of 2010 support for scalar type hinting was added to the PHP trunk.


1 Answers

http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration

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

<?php function test(boolean $param) {} test(true); ?> 

The above example will output:

Fatal error: Uncaught TypeError: Argument 1 passed to test() must be an instance of boolean, boolean given

So in a nutshell, boolean is an alias for bool, and aliases don't work in type hints.
Use the "real" name: bool


There are no similarity between Type Hinting and Type Casting.

Type hinting is something like that you are telling your function which type should be accepted.

Type casting is to "switching" between types.

The casts allowed are:

(int), (integer) - cast to integer (bool), (boolean) - cast to boolean (float), (double), (real) - cast to float (string) - cast to string (array) - cast to array (object) - cast to object (unset) - cast to NULL (PHP 5) 

In php type casting both (bool) and (boolean) are the same.

like image 155
3 revs, 3 users 49% Avatar answered Sep 24 '22 00:09

3 revs, 3 users 49%