Data type overview in phpDocumentor

Why is it good to create documentation? Especially if you’re the only coder in the project! You always have this issue of what happens when someone else is going to take over your code in the future. But besides that, if you have a smart IDE you can get a lot of extra help in automatic syntax checking by documenting what data types are expected and what errors that might be thrown. PHP uses dynamic variables able to contain anything and everything (almost) but with the documentation features you’re still able to make these variables somewhat strongly typed, not for the compiler but for the IDE. That can be a huge help when searching for problems in bigger projects.

Documenting your classes and functions in PHP is an easy task using phpDocumentor. Some IDEs have build in support for this functionality right out of the box.

Here is a simple example of how to create documentation for a function.

 * Returns option value for specified option name. If local value is set then it's returned otherwise the default value is returned.
 * @param string $optionName Name to search for
 * @return string Value of option
public function GetOptionValue($optionName)

There are many different tags beside @param and @return that you can use. The documentation on how to use this documentation tool is extensive. In this post I’m mainly focusing on the data types.

Basic types
In the example above string was used as data type. Below follows a list of the most commonly used data types available to document your code. The basic data types that can be used are:

  • string
  • integer or int
  • boolean or bool
  • float or double
  • object
  • mixed – it is not known at compile time what type it’ll be
  • void – nothing is returned
  • null – a null value may be returned

Multiple types
If you know that two or more data types are possible as return values then you can specify all of them separated by the | character. Here is a short example:

@return Customer|null Returns customer if found or null otherwise

Using arrays
When specifying an array of a data type you can either use the unspecified array

@return array Returns an array of string

…or specify it more clearly by adding [] after the data type. I prefer the latter one as in this example because you’re able to specify exactly what data type you have in the array and a good IDE can help you find errors.

@return string[] Returns an array of string

It’s also possible to use multiple types with arrays but this is probably not supported by all IDEs yet.

@return (string|int)[] Returns array of string or int