Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can PHP Functions accept boolean arguments when it asks for integers?

I was reading in a WordPress textbook where I found a quick description for the following function:

function is_super_admin( $user_id = false ) {...

This function determines if the user is a site admin.

However, my question is about the how PHP deals with the parameters.

The above function receives an integer parameter, and if you pass nothing to it then it will assign a default value of FALSE.

Here is my question:

FALSE is a BOOLEAN data type, and this function should accept an INTEGER data type.

So how can it be allowed to provide a boolean value, when we should provide an integer value?

like image 322
WPStudent Avatar asked Jul 24 '17 08:07

WPStudent


1 Answers

PHP 7 introduced scalar type declarations.

They come in two flavours: coercive (default) and strict. The following types for parameters can now be enforced (either coercively or strictly): strings (string), integers (int), floating-point numbers (float), and booleans (bool). They augment the other types introduced in PHP 5: class names, interfaces, array and callable.

The following line

function is_super_admin( $user_id = false ) { . . . .

does not specify the type of the paramater. If it was instead:

function is_super_admin( int $user_id = false ) { . . . .

then it would produce an error.

I'm guessing it defaults to false since it is easier to check for a valid value using a simple if since both false and/or an int equal to 0 evaluates to false.

More on PHP 7 new features here.

like image 177
Sotiris Kiritsis Avatar answered Sep 28 '22 19:09

Sotiris Kiritsis