PHP后台接口的一些问题

查看:105
本文介绍了PHP后台接口的一些问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

1.用PHP作后台 关于一些接口的编写问题。用
try{

if(empty($a) || !isset($a)){
    throw new Exception("***")
}

} catch (Exception $e){

echo $e->getMessage();

}

和 用
if(isset($a) && !empty($a)){

}

哪种好 有区别么

解决方案

异常处理和条件判断,很明显不是一个层面的东西!异常处理可以帮助程序增加可维护性,举例如下:

函数和函数调用场景中

使用条件判断的话代码如下:

<?php
function hello($name){
    if(empty($name)){
        return -1;
    }
    return "hello ".$name;
}
$result = hello('kobe');
if($result===-1){
    echo "姓名不能为空";
}else{
    echo $result;
}

如果使用异常处理的代码如下:

<?php
function hello($name){
    if(empty($name)){
        throw new Exception("姓名不能为空");
    }
    return "hello ".$name;
}
try{
    $result = hello();
    echo $result;
}catch (Exception $e){
    echo $e->getMessage();
}

现在我们假设使用条件判断增加参数或者修改错误返回代码为-2,都需要修改外部调用代码

但是如果我们用异常处理的代码,外部因为是通过try catch来捕获的,所有只需要关心如何修改业务逻辑的代码即可,比如

<?php
function hello($name,$age){
    if(empty($name)){
        throw new Exception("姓名不能为空");
    }
    if(empty($age)){
        throw new Exception("年龄不能为空");
    }
    return "hello ".$name ." $age";
}
try{
    $result = hello($name);//只需要修改这一部分业务逻辑代码
    echo $result;
}catch (Exception $e){
    echo $e->getMessage();
}

这篇关于PHP后台接口的一些问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆