php - 拥有更有效的代码以返回错误

标签 php performance error-handling coding-style server-side

我创建了一个主类,其中所有主要成员激活停用功能均已完成,并且与它们相关的所有其他操作也已完成

这个主类(以及一些主要功能)从各个地方被调用,包括通过curl

现在让我们在类中使用我的激活函数(主要函数之一)

activationFunction($data)
{
//use data to generate total, discount etc

$this->giveAffiliates($total);
if($this->_error){ return $this->_error;}

$this->activateOrder($total,$discount,id);
if($this->_error){ return $this->_error;}

$this->activatePlan($total,$discount,id);
if($this->_error){ return $this->_error;}

//similarily calling various functions which themselves call other functions

}

activatePlan()
{

try{

//call other functions and do necessary stuff for plan A

 }
catch(Exception $e)
{

$this->_error.="Error occurred while activating plan A";

}
//for plan B
try{

//call other functions and do necessary stuff for plan B

}
catch(Exception $e)
{

$this->_error.="Error occurred while activating plan B";

}

//for other plans similarily

 }
 }

现在的问题是每个子函数调用后都有if($this->_error){ return $this->_error;}(总共我大约有35条类似的行)
我需要这样做,因为我需要将错误发送给用户并阻止代码进一步运行。
但这使我的代码冗长且效率低下。
我如何减少所有这些返回值,但是当其中一个子函数失败并向用户显示错误并尝试保持我的代码结构不变时。
我必须从每个主函数调用各种子函数(这不能更改,其中只有一个类和各种函数),并且大多数情况下必须在每个级别捕获并返回错误(很少有简单错误不会返回并允许代码继续运行)。
我还必须记住,以后可以添加其他各种功能,并且它应该足够灵活以便以后处理所有这些功能。

最佳答案

您说“这使我的代码冗长且效率低下。”您到底是什么意思?您是说代码很慢吗?

如果您的代码速度太慢,则需要使用XDebug之类的工具来分析代码,以准确找出您的代码速度缓慢的位置。如果您不进行测量,则只是在猜测问题所在。

关于php - 拥有更有效的代码以返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16367378/

相关文章:

php - 哪个是共享数据库数据的最佳可行解决方案?

php - MySQL 服务器已经消失服务器上的错误

python - 从 Python smtplib 捕获调试输出

php - 如何去除字符串前后的空格?

php - 从 github 下载 Laravel 项目

c++ - 在 OpenGL 中重新排列数组时的效率

c++ - 将共享指针还是原始指针传递给函数

C++:去虚拟化叶子类

laravel - 在 laravel 5.2 中无法使用自定义 HTTP 错误页面

python - PYTHON : TypeError: 'NoneType' object has no attribute '__getitem__' for TESTCASE