What are the common mistakes made in php

藏色散人
Release: 2023-03-10 15:18:01
Original
1706 people have browsed it

Common mistakes made by PHP are: 1. Leaving dangling pointers after the foreach loop; 2. Misunderstanding of the behavior of isset() function; 3. Confusing return values ​​and return references; 4. Executing in a loop sql query; 5. Inefficient memory usage and illusion; 6. Ignoring Unicode/UTF-8 issues, etc.

What are the common mistakes made in php

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

What are the common mistakes made by php?

Ten common mistakes when learning PHP

Error 1: Leaving a dangling pointer after the foreach loop

In the foreach loop, if we need to change the iterated elements or to improve efficiency, using references is a good way:

$arr = array(1,2,3,4);
foreach($arr as&$value){
    $value = $value *2;
}
// $arr is now array(2, 4, 6, 8)
Copy after login

There is a question here that many people will be confused about. After the loop ends, $value is not destroyed. $value is actually a reference to the last element in the array. If you don't know this in the subsequent use of $value, it will cause some inexplicable errors:) Take a look below. This code:

$array =[1,2,3];
echo implode(',', $array),"\n";
foreach($array as&$value){}    // by reference
echo implode(',', $array),"\n";
foreach($array as $value){}     // by value (i.e., copy)
echo implode(',', $array),"\n";
Copy after login

The result of running the above code is as follows:

1,2,3
1,2,3
1,2,2
Copy after login

Did you guess it right? Why is this result?

Let’s analyze it. After the first loop, $value is a reference to the last element in the array. The second loop begins:

The first step: copy $arr[0] to $value (note that $value is a reference to $arr[2] at this time), then the array becomes [1,2 ,1]

Step 2: Copy $arr[1] to $value, then the array becomes [1,2,2]

Step 3: Copy $arr[2 ] to $value, then the array becomes [1,2,2]

To sum up, the final result is 1,2,2

The best way to avoid this error is to Use the unset function to destroy the variable immediately after the loop:

$arr = array(1,2,3,4);
foreach($arr as&$value){
    $value = $value *2;
}
unset($value);   // $value no longer references $arr[3]
Copy after login

Error 2: Wrong understanding of the isset() function behavior

For the isset() function, when the variable does not exist False will be returned, and false will also be returned when the variable value is null. This behavior can easily confuse people. . . Look at the following code:

$data = fetchRecordFromStorage($storage, $identifier);
if(!isset($data['keyShouldBeSet']){
    // do something here if 'keyShouldBeSet' is not set
}
Copy after login

The person who wrote this code may have intended that if $data[‘keyShouldBeSet’] is not set, the corresponding logic will be executed. But the problem is that even if $data[‘keyShouldBeSet’] has been set, but the set value is null, the corresponding logic will still be executed, which is not in line with the original intention of the code.

Here is another example:

if($_POST['active']){
    $postData = extractSomething($_POST);
}
// ...
if(!isset($postData)){
    echo 'post not active';
}
Copy after login

The above code assumes that $_POST[‘active’] is true, then $postData should be set, so isset($postData) will return true. Conversely, the above code assumes that the only way isset($postData) returns false is if $_POST[‘active’] also returns false.

Is this really the case? of course not!

Even if $_POST[‘active’] returns true, $postData may be set to null, in which case isset($postData) will return false. This goes against the intent of the code.

If the intention of the above code is only to detect whether $_POST['active'] is true, the following implementation would be better:

if($_POST['active']){
    $postData = extractSomething($_POST);
}
// ...
if($_POST['active']){
    echo 'post not active';
}
Copy after login

Determine whether a variable is actually set (distinguish between unset and set the value to null), the array_key_exists() function may be better. Refactor the first example above as follows:

$data = fetchRecordFromStorage($storage, $identifier);
if(! array_key_exists('keyShouldBeSet', $data)){
    // do this if 'keyShouldBeSet' isn't set
}
Copy after login

In addition, combined with the get_defined_vars() function, we can more reliably detect whether the variable is set in the current scope:

if(array_key_exists('varShouldBeSet', get_defined_vars())){
    // variable $varShouldBeSet exists in current scope
}
Copy after login

Error 3: Confusing return values ​​and return references

Consider the following code:

classConfig
{
    private $values =[];
    publicfunction getValues(){
        return $this->values;
    }
}
$config =newConfig();
$config->getValues()['test']='test';
echo $config->getValues()['test'];
Copy after login

Running the above code will output the following:

PHP Notice:  Undefined index: test in/path/to/my/script.php on line 21
Copy after login

What's the problem? The problem is that the above code confuses return values ​​and return references. In PHP, unless you explicitly specify a return reference, PHP returns a value for an array, which is a copy of the array. Therefore, when the above code assigns a value to the returned array, it actually assigns a value to the copied array, not the original array.

// getValues() returns a COPY of the $values array, so this adds a 'test' element
// to a COPY of the $values array, but not to the $values array itself.
$config->getValues()['test']='test';
// getValues() again returns ANOTHER COPY of the $values array, and THIS copy doesn't
// contain a 'test' element (which is why we get the "undefined index" message).
echo $config->getValues()['test'];
Copy after login

The following is a possible solution, output the copied array instead of the original array:

$vals = $config->getValues();
$vals['test']='test';
echo $vals['test'];
Copy after login

If you just want to change the original array, that is, you need to return the array reference, So how should we deal with it? The way is to display the specified return reference:

classConfig
{
    private $values =[];
    // return a REFERENCE to the actual $values array
    publicfunction&getValues(){
        return $this->values;
    }
}
$config =newConfig();
$config->getValues()['test']='test';
echo $config->getValues()['test'];
Copy after login

After modification, the above code will output test as you expect.

Let's look at another example that will make you more confused:

classConfig
{
    private $values;
    // using ArrayObject rather than array
    publicfunction __construct(){
        $this->values =newArrayObject();
    }
    publicfunction getValues(){
        return $this->values;
    }
}
$config =newConfig();
$config->getValues()['test']='test';
echo $config->getValues()['test'];
Copy after login

If you think that the "Undefined index" error will be output like the above, then you are wrong. The code will output "test" normally. The reason is that PHP returns objects by reference by default, not by value.

To sum up, when we use a function to return a value, we need to figure out whether it is a value return or a reference return. For objects in PHP, the default is to return by reference, and arrays and built-in basic types are returned by value by default. This should be distinguished from other languages ​​(many languages ​​pass arrays by reference).

Like other languages, such as Java or C#, it is a better solution to use getters or setters to access or set class properties. Of course, PHP does not support it by default and needs to be implemented by yourself:

classConfig
{
    private $values =[];
    publicfunction setValue($key, $value){
        $this->values[$key]= $value;
    }
    publicfunction getValue($key){
        return $this->values[$key];
    }
}
$config =newConfig();
$config->setValue('testKey','testValue');
echo $config->getValue('testKey');    // echos 'testValue'
Copy after login

The above code allows the caller to access or set any value in the array without giving the array public access. How does it feel :)

Error 4: Executing sql query in a loop

It is not uncommon to find code similar to the following in PHP programming:

$models =[];
foreach($inputValues as $inputValue){
    $models[]= $valueRepository->findByValue($inputValue);
}
Copy after login

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

$result = $connection->query("SELECT `x`,`y` FROM `values` WHERE `value`=". $inputValue);
Copy after login

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

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

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

$data =[];
foreach($ids as $id){
    $result = $connection->query("SELECT `x`, `y` FROM `values` WHERE `id` = ". $id);
    $data[]= $result->fetch_row();
}
Copy after login

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

$data =[];
if(count($ids)){
    $result = $connection->query("SELECT `x`, `y` FROM `values` WHERE `id` IN (". implode(',', $ids));
    while($row = $result->fetch_row()){
        $data[]= $row;
    }
}
Copy after login

错误5:内存使用低效和错觉

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

我们可以写代码来实验下(测试环境: 512MB RAM、MySQL、php-cli):

// connect to mysql
$connection =new mysqli('localhost','username','password','database');
// create table of 400 columns
$query ='CREATE TABLE `test`(`id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT';
for($col =0; $col <400; $col++){
    $query .=", `col$col` CHAR(10) NOT NULL";
}
$query .=&#39;);&#39;;
$connection->query($query);
// write 2 million rows
for($row =0; $row <2000000; $row++){
    $query ="INSERT INTO `test` VALUES ($row";
    for($col =0; $col <400; $col++){
        $query .=&#39;, &#39;. mt_rand(1000000000,9999999999);
    }
    $query .=&#39;)&#39;;
    $connection->query($query);
}
Copy after login

现在来看看资源消耗:

// connect to mysql
$connection =new mysqli(&#39;localhost&#39;,&#39;username&#39;,&#39;password&#39;,&#39;database&#39;);
echo "Before: ". memory_get_peak_usage()."\n";
$res = $connection->query(&#39;SELECT `x`,`y` FROM `test` LIMIT 1&#39;);
echo "Limit 1: ". memory_get_peak_usage()."\n";
$res = $connection->query(&#39;SELECT `x`,`y` FROM `test` LIMIT 10000&#39;);
echo "Limit 10000: ". memory_get_peak_usage()."\n";
Copy after login

输出结果如下:

Before:224704
Limit1:224704
Limit10000:224704
Copy after login

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

PHP Warning:  mysqli::query():(HY000/2013):
     Lost connection to MySQL server during query in/root/test.php on line 11
Copy after login

这是怎么回事呢?

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

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

Before:232048
Limit1:324952
Limit10000:32572912
Copy after login

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

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

$totalNumberToFetch =10000;
$portionSize =100;
for($i =0; $i <= ceil($totalNumberToFetch / $portionSize); $i++){
    $limitFrom = $portionSize * $i;
    $res = $connection->query(
                         "SELECT `x`,`y` FROM `test` LIMIT $limitFrom, $portionSize");
}
Copy after login

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

错误6:忽略Unicode/UTF-8问题

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

如果你对unicode和utf-8不是很了解,那么你至少应该了解一些基础。推荐阅读这篇文章。

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

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

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

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

在此推荐一篇文章,更详细的介绍了此类问题: UTF-8 Primer for PHP and MySQL

错误7:假定$_POST总是包含POST数据

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

// js
$.ajax({
    url:&#39;http://my.site/some/path&#39;,
    method:&#39;post&#39;,
    data: JSON.stringify({a:&#39;a&#39;, b:&#39;b&#39;}),
    contentType:&#39;application/json&#39;
});
Copy after login

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

// php
var_dump($_POST);
Copy after login

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

array(0){}
Copy after login

为什么是这样的结果呢?我们的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变量。

// php
$_POST = json_decode(file_get_contents(&#39;php://input&#39;),true);
Copy after login

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

array(2){["a"]=>string(1)"a"["b"]=>string(1)"b"}
Copy after login

错误8:认为PHP支持字符数据类型

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

for($c =&#39;a&#39;; $c <=&#39;z&#39;; $c++){
    echo $c ."\n";
}
Copy after login

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

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

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

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

for($i = ord(&#39;a&#39;); $i <= ord(&#39;z&#39;); $i++){
    echo chr($i)."\n";
}
Copy after login

或者这样也是OK的:

$letters = range(&#39;a&#39;,&#39;z&#39;);
for($i =0; $i < count($letters); $i++){
    echo $letters[$i]."\n";
}
Copy after login

错误9:忽略编码标准

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

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

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

PSR-0:自动加载标准

PSR-1:基本编码标准

PSR-2:编码风格指南

PSR-3:日志接口标准

PSR-4:自动加载

PSR最初由PHP社区的几个大的团体所创建并遵循。Zend, Drupal, Symfony, Joomla及其它的平台都为此标准做过贡献并遵循这个标准。即使是PEAR,早些年也想让自己成为一个标准,但现在也加入了PSR阵营。

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

错误10:错误使用empty()函数

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

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

// PHP 5.0 or later:
$array =[];
var_dump(empty($array));        // outputs bool(true)  
$array =newArrayObject();
var_dump(empty($array));        // outputs bool(false)
// why don&#39;t these both produce the same output?
Copy after login

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

// Prior to PHP 5.0:
$array =[];
var_dump(empty($array));        // outputs bool(false)  
$array =newArrayObject();
var_dump(empty($array));        // outputs bool(false)
Copy after login

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

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

// Note that this work in ALL versions of PHP (both pre and post 5.0):
$array =[];
var_dump(count($array));        // outputs int(0)
$array =newArrayObject();
var_dump(count($array));        // outputs int(0)
Copy after login

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

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

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

classRegular
{
    public $test =&#39;value&#39;;
}
Copy after login

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

classMagic
{
    private $values =[&#39;test&#39;=>&#39;value&#39;];
    publicfunction __get($key)
    {
        if(isset($this->values[$key])){
            return $this->values[$key];
        }
    }
}
Copy after login

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

$regular =newRegular();
var_dump($regular->test);    // outputs string(4) "value"
$magic =newMagic();
var_dump($magic->test);      // outputs string(4) "value"
Copy after login

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

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

var_dump(empty($regular->test));    // outputs bool(false)
var_dump(empty($magic->test));      // outputs bool(true)
Copy after login

结果是不是很意外?

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

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

Notice:Undefined property:Regular::$nonExistantTest in/path/to/test.php on line 10
CallStack:
    0.0012     234704   1.{main}()/path/to/test.php:0
Copy after login

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

推荐学习:《PHP视频教程

The above is the detailed content of What are the common mistakes made in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template