2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPで型宣言

Posted at

PHP7以降型宣言充実しており
7.4でかなり良くなり、型宣言する機会が増えたので、まとめ

1.引数の型(タイプヒンティング)

// int型のみ
function hoge(int $num)
{
    echo $num;
}
// デフォルト値
function hoge(int $num = 0)
{
    echo $num;
}
// null許容型
function hoge(?int $num)// int $num = nullも可
{
    echo $num;
}

// オブジェクト(ex.Laravel)
function hoge(Request $request)
{
    echo $request->hoge;
}

返り値(戻り値)

// int型のみ
function hoge(int $num): int
{
    return $num;
}

// null許容
function hoge(?int $num): ?int
{
    return $num;
}

// オブジェクト(ex.Laravel)
function hoge(Request $request): Request
{
    return $request;
}

// void(returnしないメソッド)
function hoge(Request $request): void
{
    echo $request->hoge;
}

プロパティ(クラス変数)


class User
{
    // intのみ
    protected int $age;
    // デフォルト
    protected string $name = 'hoge';
    // null許容
    protected ?string $address;
    // オブジェクト
    protected Request $request;
}

せっかく7.4使ってるのにいまだにタイプヒントすらないところも多々あるので積極的に使っていきたいところ

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?