The content of this article is about the use of compact() in PHP built-in functions. It has a certain reference value. Now I share it with you. Friends in need can refer to it.
I found one when using tpshop today. The PHP built-in function is called compact(). This function creates an array composed of variables taken by the parameters. If there is an array in the parameter, the value of the variable in the array will also be obtained.
This can reduce the amount of code. For example, if
/** * 获取购物车的价格详情 * @param $cartList|购物车列表 * @return array */ public function getCartPriceInfo($cartList = null) { $total_fee = $goods_fee = $goods_num = 0; //初始化数据。商品总额/节约金额/商品总共数量 if ($cartList) { foreach ($cartList as $cartKey => $cartItem) { $total_fee += $cartItem['goods_fee']; $goods_fee += $cartItem['cut_fee']; $goods_num += $cartItem['goods_num']; } } $result = array( 'total_fee' => $total_fee, 'goods_fee' => $goods_fee, 'goods_num' => $goods_num, ); return $result; }
is changed to this, the code will be much simpler.
/** * 获取购物车的价格详情 * @param $cartList|购物车列表 * @return array */ public function getCartPriceInfo($cartList = null){ $total_fee = $goods_fee = $goods_num = 0;//初始化数据。商品总额/节约金额/商品总共数量 if($cartList){ foreach ($cartList as $cartKey => $cartItem) { $total_fee += $cartItem['goods_fee']; $goods_fee += $cartItem['cut_fee']; $goods_num += $cartItem['goods_num']; } } return compact('total_fee', 'goods_fee', 'goods_num'); }
Related recommendations:
How to use PHP built-in function fgets() to read pointer files in detail
The above is the detailed content of PHP built-in function uses compact(). For more information, please follow other related articles on the PHP Chinese website!