开发者社区> 问答> 正文

求助关于php异常处理的问题

<?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();  
 }  
?>  

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

展开
收起
落地花开啦 2016-06-13 16:58:44 1946 0
1 条回答
写回答
取消 提交回答
  • 喜欢技术,喜欢努力的人

    异常本来就是以类型为基础的
    PHP5开始, 可以对函数参数进行类型约束: http://php.net/manual/zh/language.oop5.typehinting.php

    <?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之后)两种类型。而不支持整型 和 字符串类型。

    2019-07-17 19:36:28
    赞同 展开评论 打赏
问答分类:
PHP
问答标签:
问答地址:
相关产品:
问答排行榜
最热
最新

相关电子书

更多
阿里云栖开发者沙龙PHP技术专场-深入浅出网络编程与swoole内核-吴镇宇 立即下载
PHP安全开发:从白帽角度做安全 立即下载
PHP 2017.北京 全球开发者大会——高可用的PHP 立即下载