PHPの例外処理メモ
例外処理とは、想定されているエラーに対して対応を行うことです。
例外処理の基本はこんな形。 割り算の処理で0が渡されたらエラーとします。
function func($a,$b) { if ($v === 0) { throw new Exception("エラーだよ"); } return $a / $b; } try { echo func(10,0); } catch (Exception $e) { echo $e->getMessage(); //エラーだよ }
例外処理を拡張する
例外処理を拡張するには、全ての例外処理の基盤クラスであるException
クラスを継承したクラスを作ります。
<?php class ZeroException extends Exception{} function func($v) { if ($v === 0) { throw new ZeroException("errorだよ"); } return $v; } try { $a = 0; echo func($a); } catch (ZeroException $e) { echo $e->getMessage(); }
PHPの遅延静的束縛のメモ
遅延束縛とは...
静的継承のコンテキストで呼び出し元のクラスを参照できるようになります。
https://www.php.net/manual/ja/language.oop5.late-static-bindings.php
続きを読む