#### 1. 函数传值和传引用的区别 --- 传值 : 默认情况下, 函数参数通过值传递, 所以即使在函数内部改变参数的值也不会改变函数外部的值 传引用 : 就是在函数的参数前面添加 `&` 符号, 表示函数参数必须为引用地址, 不能是一个具体的值, 在函数内部对该参数所做操作会应用函数外部的该变量 引用传递官方手册 : [https://www.php.net/manual/zh/language.references.pass.php](https://www.php.net/manual/zh/language.references.pass.php) #### 2. 传值、传引用举例 --- 传值的函数 ``` $abc = 'Hello World'; echo $abc . '<br>'; //Hello World echo strtolower($abc) . '<br>'; //hello world echo $abc . '<br>'; //Hello World ``` 传引用的函数 ```php echo '<pre>'; $arr = [3, 1, 2]; var_dump($arr);//[3, 1, 2] sort($arr); var_dump($arr);//[1, 2, 3] ``` 错误示例 以下用法将抛出异常 : `Cannot pass parameter 1 by reference`, 报错译文: 第一个参数无法通过引用传递 ``` sort([3, 1, 2]); ``` #### 3. 引用传递没有定义的变量 --- **使用示例** ```php $where = ['id' => 1, 'name' => '张三'];//查询条件 $where = where_filter($where, $fields);//构建搜索器参数 $data = User::withSearch($fields, $where)->select(); ``` **自定义函数, 用于TP6搜索器** ```php /** * 去掉数组空字符串,返回所有键 * * @param array $where * @param array $keys * @return array */ function where_filter(array $where, &$keys) { // 去掉数组里的空值 (会正常返回:false、0) $where = array_filter($where, function ($k) { return ($k === '' || $k === null) ? false : true; }); // 拿到所有键 $keys = array_keys($where); // 返回数组 return $where; } ```