sprintf
用到sprintf 的时候 如果有传递的变量 如果变量可能出现 % ,则容易出错
<?php $content = "%')('%s'"; $kind = 11; $content = sprintf($content ,$kind); var_dump($content ); //输出 PHP Warning: sprintf(): Too few arguments in /home/phpmianshi/test.php on line 5 bool(false)
解决方案:
可以提前转换下 % 为 %%
$content = str_replace('%','%%',$content );
json_encode
json_encode是不支持 resource类型,报错:
PHP Warning: json_encode(): type is unsupported, encoded as null
$mysql_link = mysql_link(); function test($mysql_link){ json_encode(func_get_args()); } test($mysql_link);
strtotime
只要涉及到大小月的最后一天
<?php var_dump(date("Y-m-d", strtotime("-1 month", strtotime("2017-03-31")))); //输出2017-03-03 var_dump(date("Y-m-d", strtotime("+1 month", strtotime("2017-08-31")))); //输出2017-10-01 var_dump(date("Y-m-d", strtotime("next month", strtotime("2017-01-31")))); //输出2017-03-03 var_dump(date("Y-m-d", strtotime("last month", strtotime("2017-03-31")))); //输出2017-03-03
原理:
1. 先做-1 month, 那么当前是07-31, 减去一以后就是06-31.
2. 再做日期规范化, 因为6月没有31号, 所以就好像2点60等于3点一样, 6月31就等于了7月1
解决方案:
从PHP5.3开始呢, date新增了一系列修正短语, 来明确这个问题, 那就是"first day of" 和 "last day of", 也就是你可以限定好不要让date自动"规范化"
<?php var_dump(date("Y-m-d", strtotime("last day of -1 month", strtotime("2017-03-31")))); //输出2017-02-28 var_dump(date("Y-m-d", strtotime("first day of +1 month", strtotime("2017-08-31")))); //输出2017-09-01 var_dump(date("Y-m-d", strtotime("first day of next month", strtotime("2017-01-31")))); //输出2017-02-01 var_dump(date("Y-m-d", strtotime("last day of last month", strtotime("2017-03-31")))); //输出2017-02-28
foreach
foreach循环后留下悬挂指针
$array = [1, 2, 3]; print_r($array); foreach ($array as &$value) { } print_r($array); foreach ($array as $value) { } print_r($array); #结果: Array ( [0] => 1 [1] => 2 [2] => 3 ) Array ( [0] => 1 [1] => 2 [2] => 3 ) Array ( [0] => 1 [1] => 2 [2] => 2 )
原理:循环结束后,$value并未销毁,$value其实是数组中最后一个元素的引用
第一步:复制$arr[0]到$value(注意此时$value是$arr[2]的引用),这时数组变成[1,2,1]
第二步:复制$arr[1]到$value,这时数组变成[1,2,2]
第三步:复制$arr[2]到$value,这时数组变成[1,2,2]
解决方案:
避免这种错误最好的办法就是在循环后立即用unset函数销毁变量 或者 少用引用
isset
对于isset()函数,变量不存在时会返回false,变量值为null时也会返回false
解决方案:
判断一个变量是否真正被设置(区分未设置和设置值为null),array_key_exists()函数或许更好
- 本文固定链接: https://www.phpmianshi.com/?id=193
- 转载请注明: admin 于 PHP面试网 发表
《本文》有 0 条评论