php是弱类型语言,catch中为什么要写Exception $e ,而不是直接写$e?

<?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();  
 }  
?>
叮当猫咪
浏览 88回答 1
1回答

慕田峪7331174

异常本来就是以类型为基础的啊PHP5开始, 可以对函数参数进行类型约束:<?php//如下面的类class&nbsp;MyClass{&nbsp;&nbsp;&nbsp;&nbsp;/** &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*&nbsp;测试函数 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*&nbsp;第一个参数必须为类OtherClass的一个对象 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*/ &nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;function&nbsp;test(OtherClass&nbsp;$otherclass)&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;echo&nbsp;$otherclass->var; &nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;&nbsp;&nbsp;/** &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*&nbsp;另一个测试函数 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*&nbsp;第一个参数必须为数组&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*/ &nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;function&nbsp;test_array(array&nbsp;$input_array)&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print_r($input_array); &nbsp;&nbsp;&nbsp;&nbsp;} }//另外一个类class&nbsp;OtherClass&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;$var&nbsp;=&nbsp;'Hello&nbsp;World'; }类型约束只支持对象 和 数组(php 5.1之后)两种类型。而不支持整型 和 字符串类型。
打开App,查看更多内容
随时随地看视频慕课网APP