How to declare hexadecimals on a PHPDoc Block

Submitted by on

TL;DR: For PHP Hexadecimals, Decimals and Octals are all Integers, so they must be declared as @param integer

While I was working on a patch I had to write the docblock of a function which received a hexadecimal number and I wasn't sure what I was supposed to put in the @type param.

I went to Drupal's API documentation and comments standards page to see which is the best type for this param and I found the following:

Data types can be primitive types (int, string, etc.), complex PHP built-in types (array, object, resource), or PHP classes.

Alright, a hexadecimal number is not a complex PHP built-in type nor a PHP Class so it must be a primitive type, so I went to the PHP documentation page to see which primitives PHP has and I found the following:

  • boolean
  • integer
  • float (floating-point number, aka double)
  • String

So there wasn't a specific reference for a Hexadecimal number...

The solution:

In the end Pieter Frenssen helped me (Thanks!) with this, and he showed me that in PHP, it doesn't matter what the base number is and it can be an octal, hexadecimal or a decimal, for PHP they all are integers (which makes sense but I wanted to be sure) and he shared this small snippet where we can see that PHP sees the numbers as integers and the base doesn't matter:

$ php -a
Interactive shell

php > var_dump(gettype(0x0f));
string(7) "integer"

php > var_dump(0x08 === 8);
bool(true)

So if you are writing the documentation of a function in which one of its params is a hexadecimal number you must declare it as Integer.

Comments

Submitted by Barney on Wed, 11/15/2017 - 08:56

As you say, for PHP they are all integers. For me they are all integers too - decimal, hexadecimal and octal are just different ways of writing them down. So I'm not sure why you'd have a "function in which one of its params is a hexadecimal number". Isn't the param just a number?

When the program is actually running the number in memory is stored in binary, but we don't generally need to care about that, we just think of it as a number.

Submitted by on Wed, 11/15/2017 - 15:28

You are totally right, In the issue that I was working on the method expects one of 3 possible hexadecimal numbers so I wasn't sure if I needed to declare that param with an explicit type in the phpdoc block but as you said it doesn't matter, I could pass the decimal equivalent number and it will work, it may sound too obvious now but it wasn't for me when I was working on the patch.

And I wrote this just in case if somebody in the future has problems understanding that doesn't matter the format (hexadecimal, octal, decimal) the param must be declared as integer (because actually is an integer just with different format) in a docblock.

Thanks for your comment.

Add new comment