Home > Backend Development > PHP Tutorial > php异常处理

php异常处理

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-06 20:50:28
Original
1018 people have browsed it

<code><?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();  
 }  
?>  
</code>
Copy after login
Copy after login

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

回复内容:

<code><?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();  
 }  
?>  
</code>
Copy after login
Copy after login

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

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

PHP5开始, 可以对函数参数进行类型约束: http://php.net/manual/zh/language.oop5.typehinting.php

<code><?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';
}
</code>
Copy after login

类型约束只支持对象 和 数组(php 5.1之后)两种类型。而不支持整型 和 字符串类型。

对,有点像java

Related labels:
php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template