6

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?

Frits
  • 7,341
  • 10
  • 42
  • 60
WPStudent
  • 81
  • 1
  • 4
  • 1
    You're not declaring anywhere that the parameter is an `int`, why *shouldn't* it work? – deceze Jul 24 '17 at 08:50
  • PHP is dynamically typed. You can pass arguments of different types, unless specifically type-hinted otherwise. In this particular case, you can basically pass anything. – Mjh Jul 24 '17 at 08:50
  • Read more about [type juggling](http://php.net/manual/en/language.types.type-juggling.php) in PHP. – axiac Jul 24 '17 at 08:50
  • `is_super_admin()` is a user defined function in WordPress. You can find this function in file `/wp-includes/capabilities.php`. PHP function arguments are dynamic typed, If you don't declare as strict typed. In this function argument `$user_id` is dynamic. `$user_id` can accept any kinds of DataType. – Sumon Sarker Jul 24 '17 at 09:06

1 Answers1

10

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.

Sotiris Kiritsis
  • 3,178
  • 3
  • 23
  • 31