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
  •  | 
  •  

문제

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.

도움이 되었습니까?

해결책

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)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top