PHP Conference Japan 2024

InvalidArgumentException 類別

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

簡介

當引數不是預期類型時拋出的例外。

類別概要

class InvalidArgumentException extends LogicException {
/* 繼承的屬性 */
protected 字串 $message = "";
private 字串 $string = "";
protected 整數 $code;
保護的 字串 $file = "";
保護的 整數 $line;
私有的 陣列 $trace = [];
私有的 ?Throwable $previous = null;
/* 繼承的方法 */
公開的 Exception::__construct(字串 $message = "", 整數 $code = 0, ?Throwable $previous = null)
最終 公開的 Exception::getMessage(): 字串
最終 公開的 Exception::getCode(): 整數
最終 公開的 Exception::getFile(): 字串
最終 公開的 Exception::getLine(): 整數
最終 公開的 Exception::getTrace(): 陣列
}
新增註釋

使用者貢獻的註釋 1 則註釋

Joey at anti-culture dot net
13 年前
在我看來,這個例外對於驗證參數來說非常寶貴——例如,提供類似 C 語言的嚴格類型。

<?php
function tripleInteger($int)
{
if( !
is_int($int) )
throw new
InvalidArgumentException('tripleInteger 函式只接受整數。輸入值為:'.$int);
return
$int * 3;
}

$x = tripleInteger(4); //$x == 12
$x = tripleInteger(2.5); //會拋出例外,因為 2.5 是浮點數
$x = tripleInteger('foo'); //會拋出例外,因為 'foo' 是字串
$x = tripleInteger('4'); //會拋出例外,因為 '4' 也是字串

?>
To Top