0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【初心者向け】PHPDocの書き方まとめ(@param / @return / @throwsとは?)

0
Last updated at Posted at 2026-02-16

はじめに

PHPを書いているとよく見るこれ👇

/**
 * 記事を取得する
 *
 * @param string $article_uuid
 * @return Article|null
 */

これが PHPDoc(PHPドック) です。


今回は、
▪️PHPDocとは何か?

▪️@param とは?

▪️@return とは?

▪️@throws とは?

▪️Laravelでの実例

を初心者向けにまとめます。

PHPDocとは?

PHPDocとは、
クラスやメソッドの説明を書くための特別なコメント形式

通常のコメントは

//

ですが、PHPDocは

/**
 * コメント
 */

この形式で書きます。

なぜ書くの?

主な理由は3つ:
①:IDE(VSCode・PhpStorm)の補完が強くなる

②:他の人がコードを読みやすくなる

③:例外や戻り値の設計を明確にできる

→ 特にチーム開発ではほぼ必須です。

@param とは?

@param とは、
「このメソッドはどんな引数を受け取るのか?」を書くタグ

書き方:

@param  $変数名 説明

/**
 * 記事を取得する
 *
 * @param string $article_uuid 記事のuuid
 */
public function find(string $article_uuid)

意味:

▪️string型

▪️$article_uuidという変数

▪️投稿のUUIDを渡す想定

@return とは?

@return とは、
「このメソッドは何を返すのか?」を書くタグ

書き方:

@return  説明

/**
 * @return Article|null 記事モデル(存在しない場合はnull)
 */

意味:

▪️Article型を返す

▪️もしくはnull

型宣言あるのに必要?

PHP8以降はこう書けます:

public function find(string $article_uuid): ?Article

なので、単純な場合は必須ではありません。

しかし:

▪️複雑な型

▪️Collectionの中身の型

▪️説明補足

を書くために使われます。

@throws とは?

@throws とは、
「このメソッドは例外を投げる可能性がある」と示すタグ

書き方:

@return  説明

/**
 * 記事を取得する
 *
 * @param string $article_uuid
 * @return Article
 * @throws ArticleNotFoundException
 */
public function get(string $article_uuid): Article

意味:

▪️Articleを返す

▪️ただし、見つからなければ例外を投げる

→ これは設計上かなり重要です。

Laravelでの実例(Service層)

/**
 * 投稿を取得する
 *
 * @param  string $article_uuid 記事のUUID
 * @return Article 記事モデル
 * @throws ArticleNotFoundException 記事が存在しない場合
 */
public function findArticleOrFail(string $uuid): Article
{
    $article = $this->article_repository->findByUuid($article_uuid);

    if (!$article) {
        throw new ArticleNotFoundException();
    }

    return $article;
}

ここで大事なのは:
▪️nullを返すのか?
▪️例外を投げるのか?
これを明確にすること。

PHPDocは「設計書」にもなります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?