# PHP代码优化

## 优化1：if的使用技巧之“给定初始值”

```php
if (1 == $orderState) {
   $orderTitle = '已预定';
} else {
   $orderTitle = '已售完';
}

// 优化后
$orderTitle = '已售完';
if (1 == $orderState) {
 $orderTitle = '已预定';
}
```

## 优化2：if的使用技巧之“用"&&" 替换 if

```php
if (strlen($newPwd) < 6) {
    $message = '密码长度不足!';
}

strlen($newPwd) < 6 && $message = '密码长度不足!';
```

## 优化3：if的使用技巧之“三元运算符替换”

```php
if (empty($_POST['action'])) {
    $action = 'default';
} else {
    $action = $_POST['action'];
}

//优化后
$action = empty($_POST['action']) ? 'default' : $_POST['action'];
```

## 优化4：简化“三元运算符”

```php
$action = empty($_POST['action']) ? 'default' : $_POST['action'];
// 简写后
echo $action = $_POST['action'] ?:'default' ;
//必须保证action必须是存在的，否则Notice: Undefined index: a xxx
```

## 优化5：if的使用技巧之“去掉多此一举的if”

```php
function isLeapYear($year) {
    if (($year % 4 == 0 && 100 !=0) || ($year % 400 == 0)) {
        return true;
    } else {
        return false;
    }
}
//优化后
function isLeapYear($year) {
    return ($year % 4 == 0 && 100 !=0) || ($year % 400 == 0);
}
```

比如写js的时候

```javascript
 $('#selStatus').bind('change',function(){
     $(this).val() == 'disabled' ? $('.reason').removeClass('hidden') : $('.reason').addClass('hidden');
 });
```

## 优化6：“ else if ”能如何被改进呢？

```php
if ('玄幻' == $sortname) {
    $sort = 1;
} else if ('武侠' == $sortname) {
    $sort = 2;
} else if ('言情' == $sortname) {
    $sort = 3;
} else if ('其他' == $sortname) {
    $sort = 10;
}
//优化后
switch ($sortname) {
    case '玄幻':
        $sort = 1;
        break;
    case '武侠':
        $sort = 2;
        break;
    case '言情':
        $sort = 3;
        break;
    case '其他':
        $sort = 10;
        break;
}
```

## 优化7：：表驱动法替代“else if”

```php
$sortTable = array(
    '玄幻' => 1,
    '武侠' => 2,
    '言情' => 3,
    '其他' => 10,
);
$sortId = $sortTable[$sortname];
```

## 优化8：循环语句几个要点

* 用while(true) 表示无限循环，别用for
* 特定情况下\[发邮件、采集网页]，要加延时sleep
* 循环体内尽可能不用函数或更耗资源的调用
* foreach代替while和for循环（PHP）
* 避免空循环
* 只做一件事,尽可能短，控制在50行以内
* 循环嵌套限制在3层以内

## 优化9：使用更精悍短小的代码

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

## 优化10：避免使用幻数（magic numbers）

```php
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />

//优化后
define('APP_CHARSET', 'UTF-8');
<meta http-equiv="Content-Type" content="text/html;charset={APP_CHARSET}" />
```

[幻数浅析（Magic Number）](http://blog.csdn.net/yinshitaoyuan/article/details/51233157)

将一些比较难理解的东西，定义的常量（类中），这样代码可读性高

## 优化11：中间结果赋值给变量

```php
$str = 'this_is_a_test';
$humpstr = implode('', array_map('ucfirst', explode('_', $str)));

// 优化后
$str = $str = 'this_is_a_test';
$words   = explode('_', $str);
$uWords  = array_map('ucfirst', $words);
$humpstr = implode('', $uWords);
```

## 优化12：复杂的逻辑表达式做成布尔函数

```php
if (!$hasone && $ddisfirst = 1 && $litpic == '' && empty($litpicname)) {
    $litpcname = GetImageMapDD($iurl, $cfg_ddimg_width);;
}

// 优化后
$emptyPic = ($litpic == '' && empty($litpicname));
$validFirstPic = (!$hasone && $ddisfirst);
if ($validFirstPic && $emptyPic) {
    $litpcname = GetImageMapDD($iurl, $cfg_ddimg_width);;
}
```

## 优化13：永远不要复制粘贴雷同的代码

* 相同的代码放一起让以后修改更轻松
* 可以让全局的统计和过滤器等实现方便
* 可复用的带参函数是解决雷同代码的好办法


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://phper.shujuwajue.com/phpbian-ma-ji-qiao/phpdai-ma-you-hua.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
