search
HomeBackend DevelopmentPHP TutorialPHP后台接口的一些问题

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

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

} catch (Exception $e){

<code>echo $e->getMessage();</code>

}

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

}

哪种好 有区别么

回复内容:

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

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

} catch (Exception $e){

<code>echo $e->getMessage();</code>

}

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

}

哪种好 有区别么

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

函数和函数调用场景中

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

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

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

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

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

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

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

都不好...
对于第一个例子,如果 empty($a) 是 false,那么!isset($a)必然也是false,如果 empty($a) 是 true,用户按不会进行后面的判断
对于第二个例子,相同的一个道理
所以,你的代码直接用 if (! empty($a)) 就行了。

isset更多的用来检测数组下标,例如

<code>if (isset($_POST['username'])) {
    $username = $_POST['username'];
} else {
    $username = '';
}</code>

如果不做这个检查可能会引起一个Notice级别的错误。
而对于普通的变量,常见的处理为

<code>if (empty($a)) {
    $a = 0; //因为$a可能是null, 空, 0, false,所以强调一下用0值表示。
}</code>

关于要不要使用try catch结构看你们怎么定的项目编码规范了。但是你的用法不对。

<code>if (empty($a)) {
    throw new Exception('error');
}</code>

就可以了,交给别人去捕获并处理,自己抛异常然后自己捕获是形而上学(这里的自己是指当前的域)。你想想以下两种写法有区别吗?

<code>try{
    if(empty($a))throw new Exception('error');
}catch(Exception $e) {
    die('错误');
}
if (empty($a)) die('错误');</code>

try...catch 的目标是捕捉程序运行中抛出的异常.
第一段中把整体程序都被 try 包裹,并且把业务异常当做程序异常抛出.
第二段代码也是好多项目里的写法,业务异常错误就响应个错误.
和第二段相比较,没有好或坏,只有是否符合当前项目.
这种代码设计就要看团队的开发规范.

目前我这里也是把业务异常当做代码异常抛出,在最外层catch所有的异常.
针对不同类型的异常做不同的处理,比如是否写入日志,是否报警.

你好:首先你先区别出来isset() 和 empty()不同,isset()判断的是变量或者值是否设置,至于是空不是空就不管了,而empty()判断值是否为空,并不管值是否存在,只做非空判断。

个人建议用if(isset($a) && !empty($a)){}来做判断!

个人观点!!!

我应该怎么回答这个问题

Statement
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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.