10
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?

More than 1 year has passed since last update.

【PHP8.0】名前付き引数でソースコードをわかりやすくする

Posted at

はじめに

PHP8.0から導入された名前付き引数について、業務中レビューを頂いて知りました。
忘れないように備忘録として。。

使い方

// 関数
function test(string $name, int $age) {}

// 名前付き引数を使わず呼び出し(パターン1)
test('テスト', 20);
// 名前付き引数を使わず呼び出し(パターン2)
$userName = 'テスト';
$userAge = 20;
test($userName, $userAge);

// 名前付き引数を使って呼び出し
test(name: 'テスト', age: 20);

名前付き引数を使う方法は、関数が受け取る引数の名前コロンを付けて値を渡すだけです。

function test(test関数が受け取る引数の名前: 値);

また名前付き引数を使う場合、引数の順番を変えることもできます。

// どちらでもOK
test(name: 'テスト', age: 20);
test(age: 20, name: 'テスト');

まとめ

名前付き引数を使うことで、関数呼び出しで値を直接渡したい際に、よりわかりやすいコードとなると思います!
わかりやすいソースコードの実装の一つとして使っていきたいと思います!

10
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
10
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?