Using the PHP docblocks @return tag is there a best practice for returning a boolean as an integer (i.e. 1 or 0)?

StackOverflow https://stackoverflow.com/questions/23568025

  •  19-07-2023
  •  | 
  •  

Question

Is there a cleaner way to do this?

/**
 * Will return either a 1 or 0
 * 
 * @return int|boolean
 */
public function getExitCode()
{
    return $this->exitCode;
}

It won't return a value cast as a boolean, it will be cast as an integer.

Was it helpful?

Solution

If it returns an int your documentation should say that it returns an int. However, you can describe it:

/**
* @return int 0 on success, non-zero indicates failure
*/

This allows future expansion too. What if your exit code gets changed to provide more useful information than "yes" or "no"? "no, because XYZ" could be represented with a number other than 1, and your documentation will still be correct (which means implementations of the function will not need changing unless they want to take advantage of the new information)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top