Annotations for a PHP Programmer, What it means?
As a programmer, we’ve all heard of annotations. And as a PHP programmer, we are told by our seniors to write annotations. Most programmers fail to write a proper annotation just because every other blog or resource they find has their own way to understand and write. In this blog, I will help you out to write annotations for a PHP function, variable or even a Class and where we can use it in future.
For a function, Annotation will
- tell why a function is being created, i.e., its purpose.
- tell what is mandatory/optional as an argument.
- tell what return-type it will have.
Let me give you a wireframe of what you can write for a simple function,
/**
* function to add 2 numbers
* @param int default 0
* @param int default 0
* @return int default 0
*/
public function add($a = 0, $b = 0){
return $a + $b;
}
Tips:
— If multiple(use a pipe for separation), you can specify these for a param and return-type too
int|bool|array|object(/Path/to/Class)|string|char|mixed…etc
— For an object, you can try this(specifies as object automatically):
* @param /Path/To/Class
— If dependent on any other function, you can even specify that
Let’s move on to Variables, For Annotation
- the data type and
- the purpose is enough
Here’s another wireframe for variables,
/**
* instance of this class
* @var mixed|null
*
*/
protected static $instance;
Tips:
— You can specify null too, if at any point it is going to be using a pipe(|) as a separator.
— even mixed(can be of any type) can be used too.
Comes the Godzilla, Classes
- Annotation for a class is not necessary. Period.
- However, It may contain outline of all functions which are being frequently used or publicly accessible.
Try this out for a wireframe.
/**
* @method static chapters(int $chapter=0)
* @method static calculator(string $operation, int $a=0, int|null $b)
*
*@see /Path/To/Interface
*/
Class Math implements Subject
Where we can use it in future?
That’s easy, you can generate whole documentation of your application using these annotations.
Maintaining the project for future use is super easy.
If you use annotations IDE can use this information to display popup hints when you’re writing code that works with an instance of the class. BIG BONUS
If you want to do much more with annotations, just try out php-annotations. It will give you more than just a basic idea of using annotations, i.e, for automatic validations, custom annotations, etc.
And moreover, you don’t want any other programmer reading your code to curse you, do you?