<?php //創建可拋出一個異常的函數 function checkNum($number)
{
if($number>1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}
//在 "try" 代碼塊中觸發異常 try
{
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}
//捕獲異常 catch(**Exception $e**)
{
echo 'Message: ' .$e->getMessage();
}
?>
1 回答

慕田峪7331174
TA貢獻1828條經驗 獲得超13個贊
異常本來就是以類型為基礎的啊
PHP5開始, 可以對函數參數進行類型約束:
<?php//如下面的類class MyClass{ /** * 測試函數 * 第一個參數必須為類OtherClass的一個對象 */ public function test(OtherClass $otherclass) { echo $otherclass->var; } /** * 另一個測試函數 * 第一個參數必須為數組 */ public function test_array(array $input_array) { print_r($input_array); } }//另外一個類class OtherClass { public $var = 'Hello World'; }
類型約束只支持對象 和 數組(php 5.1之后)兩種類型。而不支持整型 和 字符串類型。
- 1 回答
- 0 關注
- 102 瀏覽
添加回答
舉報
0/150
提交
取消