php异常处理
PHP中文网
PHP中文网 2017-04-10 14:26:15
[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

PHP中文网
PHP中文网

认证0级讲师

全部回复(2)
黄舟

异常本来就是以类型为基础的啊

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

伊谢尔伦

对,有点像java

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号