Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP 7 docblock and function return type?

Tags:

php

Do I have to make docblocks in php 7 if I declare my function return type?

Is it sufficient to do this for example:

public function findByLogin(string $login): User
{
    return User::where(User::COL_LOGIN, $login)->first();
}

Or should I do this:

/**
 * Find a user by its login.
 *
 * @param string $login
 * @return User
 */
public function findByLogin(string $login): User
{
    return User::where(User::COL_LOGIN, $login)->first();
}

Feels like double documentation.

like image 693
Michael Avatar asked Jan 28 '23 03:01

Michael


2 Answers

You don't need to add PHPDocs to your code - the return type declarations are fine.

Only reason to add a PHPDoc is to define even more information / more specific types.

See this example here:

/**
 * @return string[] An array of strings
 */
public function findByLogin(): array
{
    return ['foo', 'bar'];
}

So, if you are fine with return types, feel free to skip PHPDoc. If you want to give more, standardized info about params/return types: Add an additional PHPDoc.

Tools like PHPStorm help to keep parameters, return types and PHPDoc synchronous. They will show warnings if both do not match.

like image 170
Johannes N. Avatar answered Jan 30 '23 04:01

Johannes N.


It's up to you.

If a method docblock has params & return value types only it's useless and gives nothing additional info for the reader.

If the docblock gives more info (description of input params or what the method return in case of no data was found, etc.) it gives additional value and it makes sense to write it.

In your code snippet the only explanation is what the method does, but @param and @return give no additional info so I would omit them.

like image 30
pryazhnikov Avatar answered Jan 30 '23 03:01

pryazhnikov