Upgrade to Pro — share decks privately, control downloads, hide ads and more …

PHP関西勉強会LT資料.pdf

Avatar for nishimura syota nishimura syota
June 25, 2025
26

 PHP関西勉強会LT資料.pdf

Avatar for nishimura syota

nishimura syota

June 25, 2025

Transcript

  1. 型付けの威力 Before function calc($price, $rate) { return $price * $rate;

    } After function calculateTax( int $price, float $rate ): float { return $price * $rate; } 効果 実行前にエラー発見 IDEが自動補完 意図が明確 6 型を書くだけで安心感UP!
  2. 意図しない変更の問題 プロパティが予期せず変更される... class User { public $id; public $email; public

    function __construct($id, $email) { $this->id = $id; $this->email = $email; } } $user = new User(1, "[email protected]"); $user->id = 999; // 意図しない変更! 7
  3. readonly でスッキリ解決! 意図しない変更を防止 class User { public readonly int $id;

    public readonly string $email; public function __construct( int $id, string $email ) { $this->id = $id; $this->email = $email; } } $user = new User(1, "[email protected]"); // $user->id = 999; // エラー!変更不可 メリット 意図が明確 変更を防止 型安全性 8 意図しない変更をブロック!
  4. よくある問題コード class Order { public $id; public $total; public function

    __construct($id, $total) { $this->id = $id; $this->total = $total; } } $order = new Order(1, 1000); $order->total = -500; // 負の値! $order->id = null; // 不正な値! 問題点 型なし・変更可能・不正な値の代入 → バグの温床 9
  5. 型とreadonly で安全設計! class Order { public readonly int $id; public

    readonly int $total; public string $status; public function __construct(int $id, int $total) { $this->id = $id; $this->total = $total; $this->status = 'pending'; } } // $order->id = 999; // エラー!変更不可 // $order->total = -500; // エラー!変更不可 改善効果:不正な変更を防止・意図が明確・型安全性向上 10
  6. 明日から始める2ステップ 基本の型付け function getUser(int $id): ?User { // 型を明記して意図を明確に }

    readonly プロパティで安全性向上 class User { public readonly int $id; public readonly string $email; // 意図しない変更を防止 } 11