PHP代码的优化

Jackey PHP 3,034 次浏览 , 没有评论

if代码块的优化

  1. if ( 1 == $orderState ) {
  2. $status = 'success';
  3. }else{
  4. $status = 'error';
  5. }
  6. return $status;
  7.  
  8. #### 完全可以简化成如下代码
  9. $status = 'error';
  10. if ( 1 == $orderState ) {
  11. $status = 'success';
  12. }
  13. return $status;

使用三元运算符来替换if

  1. if ( !empty($_POST['action']) ) {
  2. $action = $_POST['action'];
  3. }else{
  4. $action = 'default';
  5. }
  6. #### 完全可以简化成如下代码
  7. $action = !empty($_POST['action']) ? $_POST['action'] : 'default';

中间结果赋值给变量

  1. $str = 'this_is_test';
  2. $res = implode('', array_map('ucfirst', explode('_', $str)));
  3.  
  4. #### 完全可以简化成如下代码
  5. $str = 'this_is_test';
  6. $words = explode('_', $str);
  7. $uWords = array_map('ucfirst', $words);
  8. $res = implode(' ', $uWords);

使用更加精悍短小的代码

  • 函数的最佳最大长度是 50-150行代码 ,更容易理解也方便修改
  • 函数参数 不超过7
  • 只做一件事情的函数更易于复用

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Go