简体   繁体   English

在PHP中“退出”脚本的正确方法

[英]Proper way to 'exit' a script in PHP

I have a static method named ServerResponse that basically shows a message whether on success or fail. 我有一个名为ServerResponse的静态方法,该方法基本上显示一条消息,无论成功还是失败。 I just want to know the proper way to actually display the message and exit the script. 我只想知道实际显示消息并退出脚本的正确方法。

Should I implement my method like this: 我应该像这样实现我的方法吗:

public static function ServerResponse($e,$m){

    print(json_encode([$e,$m]));
    exit;
}

//Sample use: //使用示例:

if(this happens){
    myclass::ServerResponse($x,$y);
}

or like this: 或像这样:

public static function ServerResponse($e,$m){
    return json_encode([$e,$m]);
}

//Sample use: //使用示例:

if(this happens){
    print(myclass::ServerResponse($x,$y));
    exit;
}
  • Which one is proper and better... and why? 哪一个合适且更好...为什么?
  • is there any difference between them? 它们之间有什么区别吗? (on execution time). (在执行时间上)。

"Don't be hard on me I am not an expert (just yet)..." “别对我好一点,我不是专家(只是)...”

For better debugging, it's advised to always make a function or method return a value. 为了更好地调试,建议始终使函数或方法返回值。 So your 2nd sample should be chosen. 因此,应选择第二个样本。

exit (or die ) are commonly used when the program ends with an error, giving the ability to add an exit status (as a number or a string). 当程序以错误结束时,通常使用exit (或die ),从而可以添加退出状态(以数字或字符串表示)。

I suppose there will be no significant difference about the execution time. 我想执行时间不会有显着差异。

I don't know if this is common practice but I only use exit to debug. 我不知道这是否是常见的做法,但是我只使用exit进行调试。 If your script comes to the end of execution it will exit on it's own. 如果脚本执行结束,它将自行退出。

If you must exit, do it in the main script, not in a function. 如果必须退出,请在主脚本中而不是在函数中执行。 functions should have one task and do that task. 函数应具有一项任务并执行该任务。 So the function ServerResponse should send a response and not kill the script. 因此,函数ServerResponse应该发送响应,而不是终止脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM