天天看点

PHP 编程中 10 个最常见的错误,你犯过几个?

PHP 编程中 10 个最常见的错误,你犯过几个?

<a target="_blank"></a>

在foreach循环中,如果我们需要更改迭代的元素或是为了提高效率,运用引用是一个好办法:

<code>$arr = array(1,2,3,4);</code>

<code>foreach($arr as&amp;$value){</code>

<code>    $value = $value *2;</code>

<code>}</code>

<code>// $arr is now array(2, 4, 6, 8)</code>

这里有个问题很多人会迷糊。循环结束后,$value并未销毁,$value其实是数组中最后一个元素的引用,这样在后续对$value的使用中,如果不知道这一点,会引发一些莫名奇妙的错误:)看看下面这段代码:

<code>$array =[1,2,3];</code>

<code>echo implode(',', $array),"\n";</code>

<code></code>

<code>foreach($array as&amp;$value){}    // by reference</code>

<code>foreach($array as $value){}     // by value (i.e., copy)</code>

上面代码的运行结果如下:

<code>1,2,3</code>

<code>1,2,2</code>

你猜对了吗?为什么是这个结果呢?

我们来分析下。第一个循环过后,$value是数组中最后一个元素的引用。第二个循环开始:

第一步:复制$arr[0]到$value(注意此时$value是$arr[2]的引用),这时数组变成[1,2,1]

第二步:复制$arr[1]到$value,这时数组变成[1,2,2]

第三步:复制$arr[2]到$value,这时数组变成[1,2,2]

综上,最终结果就是1,2,2

避免这种错误最好的办法就是在循环后立即用unset函数销毁变量:

<code>unset($value);   // $value no longer references $arr[3]</code>

对于isset()函数,变量不存在时会返回false,变量值为null时也会返回false。这种行为很容易把人弄迷糊。。。看下面的代码:

<code>$data = fetchrecordfromstorage($storage, $identifier);</code>

<code>if(!isset($data['keyshouldbeset']){</code>

<code>    // do something here if 'keyshouldbeset' is not set</code>

写这段代码的人本意可能是如果$data[‘keyshouldbeset’]未设置,则执行对应逻辑。但问题在于即使$data[‘keyshouldbeset’]已设置,但设置的值为null,还是会执行对应的逻辑,这就不符合代码的本意了。

下面是另外一个例子:

<code>if($_post['active']){</code>

<code>    $postdata = extractsomething($_post);</code>

<code>// ...</code>

<code>if(!isset($postdata)){</code>

<code>    echo 'post not active';</code>

上 面的代码假设$_post[‘active’]为真,那么$postdata应该被设置,因此isset($postdata)会返回true。反之,上 面代码假设isset($postdata)返回false的唯一途径就是$_post[‘active’]也返回false。

真是这样吗?当然不是!

即使$_post[‘active’]返回true,$postdata也有可能被设置为null,这时isset($postdata)就会返回false。这就不符合代码的本意了。

如果上面代码的本意仅是检测$_post[‘active’]是否为真,下面这样实现会更好:

判断一个变量是否真正被设置(区分未设置和设置值为null),array_key_exists()函数或许更好。重构上面的第一个例子,如下:

<code>if(! array_key_exists('keyshouldbeset', $data)){</code>

<code>    // do this if 'keyshouldbeset' isn't set</code>

另外,结合get_defined_vars()函数,我们可以更加可靠的检测变量在当前作用域内是否被设置:

<code>if(array_key_exists('varshouldbeset', get_defined_vars())){</code>

<code>    // variable $varshouldbeset exists in current scope</code>

考虑下面的代码:

<code>classconfig</code>

<code>{</code>

<code>    private $values =[];</code>

<code>    publicfunction getvalues(){</code>

<code>        return $this-&gt;values;</code>

<code>    }</code>

<code>$config =newconfig();</code>

<code>$config-&gt;getvalues()['test']='test';</code>

<code>echo $config-&gt;getvalues()['test'];</code>

运行上面的代码,将会输出下面的内容:

<code>php notice:  undefined index: test in/path/to/my/script.php on line 21</code>

问题出在哪呢?问题就在于上面的代码混淆了返回值和返回引用。在php中,除非你显示的指定返回引用,否则对于数组php是值返回,也就是数组的拷贝。因此上面代码对返回数组赋值,实际是对拷贝数组进行赋值,非原数组赋值。

<code>// getvalues() returns a copy of the $values array, so this adds a 'test' element</code>

<code>// to a copy of the $values array, but not to the $values array itself.</code>

<code>// getvalues() again returns another copy of the $values array, and this copy doesn't</code>

<code>// contain a 'test' element (which is why we get the "undefined index" message).</code>

下面是一种可能的解决办法,输出拷贝的数组,而不是原数组:

<code>$vals = $config-&gt;getvalues();</code>

<code>$vals['test']='test';</code>

<code>echo $vals['test'];</code>

如果你就是想要改变原数组,也就是要反回数组引用,那应该如何处理呢?办法就是显示指定返回引用即可:

<code>    // return a reference to the actual $values array</code>

<code>    publicfunction&amp;getvalues(){</code>

经过改造后,上面代码将会像你期望那样会输出test。

我们再来看一个例子会让你更迷糊的例子:

<code>    private $values;</code>

<code>    // using arrayobject rather than array</code>

<code>    publicfunction __construct(){</code>

<code>        $this-&gt;values =newarrayobject();</code>

如果你想的是会和上面一样输出“ undefined index”错误,那你就错了。代码会正常输出“test”。原因在于php对于对象默认就是按引用返回的,而不是按值返回。

综上所述,我们在使用函数返回值时,要弄清楚是值返回还是引用返回。php中对于对象,默认是引用返回,数组和内置基本类型默认均按值返回。这个要与其它语言区别开来(很多语言对于数组是引用传递)。

像其它语言,比如java或c#,利用getter或setter来访问或设置类属性是一种更好的方案,当然php默认不支持,需要自己实现:

<code>    publicfunction setvalue($key, $value){</code>

<code>        $this-&gt;values[$key]= $value;</code>

<code>    publicfunction getvalue($key){</code>

<code>        return $this-&gt;values[$key];</code>

<code>$config-&gt;setvalue('testkey','testvalue');</code>

<code>echo $config-&gt;getvalue('testkey');    // echos 'testvalue'</code>

上面的代码给调用者可以访问或设置数组中的任意值而不用给与数组public访问权限。感觉怎么样:) 

在php编程中发现类似下面的代码并不少见:

<code>$models =[];</code>

<code>foreach($inputvalues as $inputvalue){</code>

<code>    $models[]= $valuerepository-&gt;findbyvalue($inputvalue);</code>

当然上面的代码是没有什么错误的。问题在于我们在迭代过程中$valuerepository-&gt;findbyvalue()可能每次都执行了sql查询:

<code>$result = $connection-&gt;query("select `x`,`y` from `values` where `value`=". $inputvalue);</code>

如果迭代了10000次,那么你就分别执行了10000次sql查询。如果这样的脚本在多线程程序中被调用,那很可能你的系统就挂了。。。

在编写代码过程中,你应该要清楚什么时候应该执行sql查询,尽可能一次sql查询取出所有数据。

有一种业务场景,你很可能会犯上述错误。假设一个表单提交了一系列值(假设为ids),然后为了取出所有id对应的数据,代码将遍历ids,分别对每个id执行sql查询,代码如下所示:

<code>$data =[];</code>

<code>foreach($ids as $id){</code>

<code>    $result = $connection-&gt;query("select `x`, `y` from `values` where `id` = ". $id);</code>

<code>    $data[]= $result-&gt;fetch_row();</code>

但同样的目的可以在一个sql中更加高效的完成,代码如下:

<code>if(count($ids)){</code>

<code>    $result = $connection-&gt;query("select `x`, `y` from `values` where `id` in (". implode(',', $ids));</code>

<code>    while($row = $result-&gt;fetch_row()){</code>

<code>        $data[]= $row;</code>

一次sql查询获取多条记录比每次查询获取一条记录效率肯定要高,但如果你使用的是php中的mysql扩展,那么一次获取多条记录就很可能会导致内存溢出。

我们可以写代码来实验下(测试环境: 512mb ram、mysql、php-cli):

<code>// connect to mysql</code>

<code>$connection =new mysqli('localhost','username','password','database');</code>

<code>// create table of 400 columns</code>

<code>$query ='create table `test`(`id` int not null primary key auto_increment';</code>

<code>for($col =0; $col &lt;400; $col++){</code>

<code>    $query .=", `col$col` char(10) not null";</code>

<code>$query .=');';</code>

<code>$connection-&gt;query($query);</code>

<code>// write 2 million rows</code>

<code>for($row =0; $row &lt;2000000; $row++){</code>

<code>    $query ="insert into `test` values ($row";</code>

<code>    for($col =0; $col &lt;400; $col++){</code>

<code>        $query .=', '. mt_rand(1000000000,9999999999);</code>

<code>    $query .=')';</code>

<code>    $connection-&gt;query($query);</code>

现在来看看资源消耗:

<code>echo "before: ". memory_get_peak_usage()."\n";</code>

<code>$res = $connection-&gt;query('select `x`,`y` from `test` limit 1');</code>

<code>echo "limit 1: ". memory_get_peak_usage()."\n";</code>

<code>$res = $connection-&gt;query('select `x`,`y` from `test` limit 10000');</code>

<code>echo "limit 10000: ". memory_get_peak_usage()."\n";</code>

输出结果如下:

<code>before:224704</code>

<code>limit1:224704</code>

<code>limit10000:224704</code>

根据内存使用量来看,貌似一切正常。为了更加确定,试着一次获取100000条记录,结果程序得到如下输出:

<code>php warning:  mysqli::query():(hy000/2013):</code>

<code>     lost connection to mysql server during query in/root/test.php on line 11</code>

这是怎么回事呢?

问 题出在php的mysql模块的工作方式,mysql模块实际上就是libmysqlclient的一个代理。在查询获取多条记录的同时,这些记录会直接 保存在内存中。由于这块内存不属于php的内存模块所管理,所以我们调用memory_get_peak_usage()函数所获得的值并非真实使用内存 值,于是便出现了上面的问题。

我们可以使用mysqlnd来代替mysql,mysqlnd编译为php自身扩展,其内存使用由php内存管理模块所控制。如果我们用mysqlnd来实现上面的代码,则会更加真实的反应内存使用情况:

<code>before:232048</code>

<code>limit1:324952</code>

<code>limit10000:32572912</code>

更加糟糕的是,根据php的官方文档,mysql扩展存储查询数据使用的内存是mysqlnd的两倍,因此原来的代码使用的内存是上面显示的两倍左右。

为了避免此类问题,可以考虑分几次完成查询,减小单次查询数据量:

<code>$totalnumbertofetch =10000;</code>

<code>$portionsize =100;</code>

<code>for($i =0; $i &lt;= ceil($totalnumbertofetch / $portionsize); $i++){</code>

<code>    $limitfrom = $portionsize * $i;</code>

<code>    $res = $connection-&gt;query(</code>

<code>                         "select `x`,`y` from `test` limit $limitfrom, $portionsize");</code>

联系上面提到的错误4可以看出,在实际的编码过程中,要做到一种平衡,才能既满足功能要求,又能保证性能。

php编程中,在处理非ascii字符时,会遇到一些问题,要很小心的去对待,要不然就会错误遍地。举个简单的例子,strlen($name),如果$name包含非ascii字符,那结果就有些出乎意料。在此给出一些建议,尽量避免此类问题:

最好使用mb_*函数来处理字符串,避免使用老的字符串处理函数。这里要确保php的“multibyte”扩展已开启。

数据库和表最好使用unicode编码。

知道jason_code()函数会转换非ascii字符,但serialize()函数不会。

php代码源文件最好使用不含bom的utf-8格式。

php中的$_post并非总是包含表单post提交过来的数据。假设我们通过 jquery.ajax() 方法向服务器发送了post请求:

<code>// js</code>

<code>$.ajax({</code>

<code>    url:'http://my.site/some/path',</code>

<code>    method:'post',</code>

<code>    data: json.stringify({a:'a', b:'b'}),</code>

<code>    contenttype:'application/json'</code>

<code>});</code>

注意代码中的 contenttype: ‘application/json’ ,我们是以json数据格式来发送的数据。在服务端,我们仅输出$_post数组:

<code>// php</code>

<code>var_dump($_post);</code>

你会很惊奇的发现,结果是下面所示:

<code>array(0){}</code>

为什么是这样的结果呢?我们的json数据 {a: ‘a’, b: ‘b’} 哪去了呢?

答案就是php仅仅解析content-type为 application/x-www-form-urlencoded 或 multipart/form-data的http请求。之所以这样是因为历史原因,php最初实现$_post时,最流行的就是上面两种类型。因此虽说现在有些类型(比如application/json)很流行,但php中还是没有去实现自动处理。

因为$_post是全局变量,所以更改$_post会全局有效。因此对于content-type为 application/json的请求,我们需要手工去解析json数据,然后修改$_post变量。

<code>$_post = json_decode(file_get_contents('php://input'),true);</code>

此时,我们再去输出$_post变量,则会得到我们期望的输出:

<code>array(2){["a"]=&gt;string(1)"a"["b"]=&gt;string(1)"b"}</code>

看看下面的代码,猜测下会输出什么:

<code>for($c ='a'; $c &lt;='z'; $c++){</code>

<code>    echo $c ."\n";</code>

如果你的回答是输出’a’到’z’,那么你会惊奇的发现你的回答是错误的。

不错,上面的代码的确会输出’a’到’z’,但除此之外,还会输出’aa’到’yz’。我们来分析下为什么会是这样的结果。

在php中不存在char数据类型,只有string类型。明白这点,那么对’z’进行递增操作,结果则为’aa’。对于字符串比较大小,学过c的应该都知道,’aa’是小于’z’的。这也就解释了为何会有上面的输出结果。

如果我们想输出’a’到’z’,下面的实现是一种不错的办法:

<code>for($i = ord('a'); $i &lt;= ord('z'); $i++){</code>

<code>    echo chr($i)."\n";</code>

或者这样也是ok的:

<code>$letters = range('a','z');</code>

<code>for($i =0; $i &lt; count($letters); $i++){</code>

<code>    echo $letters[$i]."\n";</code>

<code>}</code> 

虽说忽略编码标准不会导致错误或是bug,但遵循一定的编码标准还是很重要的。

没有统一的编码标准会使你的项目出现很多问题。最明显的就是你的项目代码不具有一致性。更坏的地方在于,你的代码将更加难以调试、扩展和维护。这也就意味着你的团队效率会降低,包括做一些很多无意义的劳动。

对于php开发者来说,是比较幸运的。因为有php编码标准推荐(psr),由下面5个部分组成:

<a href="http://www.php-fig.org/psr/psr-0/" target="_blank">psr-0:自动加载标准</a>

<a href="http://www.php-fig.org/psr/psr-1/" target="_blank">psr-1:基本编码标准</a>

<a href="http://www.php-fig.org/psr/psr-2/" target="_blank">psr-2:编码风格指南</a>

<a href="http://www.php-fig.org/psr/psr-3/" target="_blank">psr-3:日志接口标准</a>

<a href="http://www.php-fig.org/psr/psr-4/" target="_blank">psr-4:自动加载</a>

psr最初由php社区的几个大的团体所创建并遵循。zend, drupal, symfony, joomla及其它的平台都为此标准做过贡献并遵循这个标准。即使是pear,早些年也想让自己成为一个标准,但现在也加入了psr阵营。

在 某些情况下,使用什么编码标准是无关紧要的,只要你使用一种编码风格并一直坚持使用即可。但是遵循psr标准不失为一个好办法,除非你有什么特殊的原因要 自己弄一套。现在越来越多的项目都开始使用psr,大部分的php开发者也在使用psr,因此使用psr会让新加入你团队的成员更快的熟悉项目,写代码时 也会更加舒适。 

一些php开发人员喜欢用empty()函数去对变量或表达式做布尔判断,但在某些情况下会让人很困惑。

首先我们来看看php中的数组array和数组对象arrayobject。看上去好像没什么区别,都是一样的。真的这样吗?

<code>// php 5.0 or later:</code>

<code>$array =[];</code>

<code>var_dump(empty($array));        // outputs bool(true)  </code>

<code>$array =newarrayobject();</code>

<code>var_dump(empty($array));        // outputs bool(false)</code>

<code>// why don't these both produce the same output?</code>

让事情变得更复杂些,看看下面的代码:

<code>// prior to php 5.0:</code>

<code>var_dump(empty($array));        // outputs bool(false)  </code>

很不幸的是,上面这种方法很受欢迎。例如,在zend framework 2中,zend\db\tablegateway 在 tablegateway::select() 结果集上调用 current() 方法返回数据集时就是这么干的。开发人员很容易就会踩到这个坑。

为了避免这些问题,检查一个数组是否为空最后的办法是用 count() 函数:

<code>// note that this work in all versions of php (both pre and post 5.0):</code>

<code>var_dump(count($array));        // outputs int(0)</code>

在这顺便提一下,因为php中会将数值0认为是布尔值false,因此 count() 函数可以直接用在 if 条件语句的条件判断中来判断数组是否为空。另外,count() 函数对于数组来说复杂度为o(1),因此用 count() 函数是一个明智的选择。

再来看一个用 empty() 函数很危险的例子。当在魔术方法 __get() 中结合使用 empty() 函数时,也是很危险的。我们来定义两个类,每个类都有一个 test 属性。

首先我们定义 regular 类,有一个 test 属性:

<code>classregular</code>

<code>    public $test ='value';</code>

然后我们定义 magic 类,并用 __get() 魔术方法来访问它的 test 属性:

<code>classmagic</code>

<code>    private $values =['test'=&gt;'value'];</code>

<code>    publicfunction __get($key)</code>

<code>    {</code>

<code>        if(isset($this-&gt;values[$key])){</code>

<code>            return $this-&gt;values[$key];</code>

<code>        }</code>

好了。我们现在来看看访问各个类的 test 属性会发生什么:

<code>$regular =newregular();</code>

<code>var_dump($regular-&gt;test);    // outputs string(4) "value"</code>

<code>$magic =newmagic();</code>

<code>var_dump($magic-&gt;test);      // outputs string(4) "value"</code>

到目前为止,都还是正常的,没有让我们感到迷糊。

但在 test 属性上使用 empty() 函数会怎么样呢?

<code>var_dump(empty($regular-&gt;test));    // outputs bool(false)</code>

<code>var_dump(empty($magic-&gt;test));      // outputs bool(true)</code>

结果是不是很意外?

很不幸的是,如果一个类使用魔法 __get() 函数来访问类属性的值,没有简单的方法来检查属性值是否为空或是不存在。在类作用域外,你只能检查是否返回 null 值,但这并不一定意味着没有设置相应的键,因为键值可以被设置为 null 。

相比之下,如果我们访问 regular 类的一个不存在的属性,则会得到一个类似下面的notice消息:

<code>notice:undefined property:regular::$nonexistanttest in/path/to/test.php on line 10</code>

<code>callstack:</code>

<code>    0.0012     234704   1.{main}()/path/to/test.php:0</code>

因此,对于 empty() 函数,我们要小心的使用,要不然的话就会结果出乎意料,甚至潜在的误导你。

本文来自云栖社区合作伙伴“linux中国”,原文发布日期:2015-10-13