Home  >  Article  >  Backend Development  >  What are the common errors in php?

What are the common errors in php?

青灯夜游
青灯夜游Original
2019-10-11 17:31:532298browse

PHP is a very popular open source server-side scripting language. Most of the websites you see on the World Wide Web are developed using PHP. This article will introduce you to the 10 most common problems in PHP development. I hope it can be helpful to your friends.

What are the common errors in php?

Error 1: leaving dangling pointer after foreach loop

In foreach loop, if we need to change the iterated element or In order to improve efficiency, using quotes 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)

There is a problem here that many people will be confused about. After the loop ends, value is actually a reference to the last element in the array. If you don't know this in the subsequent use of $value, some inexplicable errors will occur:) Take a look at the following 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";

The result of running the above code is as follows:

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 starts:

● Step 1: Copy value (note the reference of arr[2] at this time), then the array becomes [1,2,1]

● Step 2: Copy value, then the array becomes [1,2,2]

● Step 3: Copy 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]

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

For the isset() function, false will be returned when the variable does not exist, and false will 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 
}

The person who wrote this code may have intended that if data['keyShouldBeSet'] has been set, but the set value is null, the corresponding logic will still be executed, which is inconsistent with the code. the original intention.

Here is another example:

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

The above code assumes that postData should be set, so the only way isset(postData) returns false is if $_POST['active'] also returns false.

Is this really the case? of course not!

Even 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'; 
}

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 
}

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 
}

Error 3: Confusing return values ​​and return references

Consider the following code:

class Config 
{ 
  private $values = []; 
 
  public function getValues() { 
    return $this->values; 
  } 
} 
 
$config = new Config(); 
 
$config->getValues()['test'] = 'test'; 
echo $config->getValues()['test'];

Running the above code will output the following:

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

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'];

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

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

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:

class Config 
{ 
  private $values = []; 
 
  // return a REFERENCE to the actual $values array 
  public function &getValues() { 
    return $this->values; 
  } 
} 
 
$config = new Config(); 
 
$config->getValues()['test'] = 'test'; 
echo $config->getValues()['test'];

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

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

class Config 
{ 
  private $values; 
 
  // using ArrayObject rather than array 
  public function __construct() { 
    $this->values = new ArrayObject(); 
  } 
 
  public function getValues() { 
    return $this->values; 
  } 
} 
 
$config = new Config(); 
 
$config->getValues()['test'] = 'test'; 
echo $config->getValues()['test'];

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 attributes. Of course, PHP does not support it by default and needs to be implemented by yourself:

class Config 
{ 
  private $values = []; 
 
  public function setValue($key, $value) { 
    $this->values[$key] = $value; 
  } 
 
  public function getValue($key) { 
    return $this->values[$key]; 
  } 
} 
 
$config = new Config(); 
 
$config->setValue('testKey', 'testValue'); 
echo $config->getValue('testKey');  // echos 'testValue'

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); 
}

Of course there is nothing wrong with the above code. The problem is that $valueRepository->findByValue() may execute the sql query every time during the iteration process:

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

If it is iterated 10,000 times, then you have executed 10,000 sql queries respectively. If such a script is called in a multi-threaded program, it is likely that your system will hang. . .

In the process of writing code, you should know when to execute the sql query, and try to retrieve all the data in one sql query.

有一种业务场景,你很可能会犯上述错误。假设一个表单提交了一系列值(假设为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(); 
}

但同样的目的可以在一个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; 
  } 
}

错误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); 
}

现在来看看资源消耗:

// 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";

输出结果如下:

Before: 224704 
Limit 1: 224704 
Limit 10000: 224704

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

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

这是怎么回事呢?

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

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

Before: 232048 
Limit 1: 324952 
Limit 10000: 32572912

更加糟糕的是,根据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"); 
}

联系上面提到的错误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格式。

错误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;
});

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

// php 
var_dump($_POST);

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

array(0) { }

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

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

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

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

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

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

如果你的回答是输出'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"; 
}

或者这样也是OK的:

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

错误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 = new ArrayObject(); 
var_dump(empty($array));    // outputs bool(false) 
// why don&#39;t these both produce the same output?

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

// Prior to PHP 5.0: 
$array = []; 
var_dump(empty($array));    // outputs bool(false) 
$array = new ArrayObject(); 
var_dump(empty($array));    // outputs bool(false)

很不幸的是,上面这种方法很受欢迎。例如,在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 = new ArrayObject(); 
var_dump(count($array));    // outputs int(0)

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

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

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

class Regular 
{ 
  public $test = &#39;value&#39;; 
}

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

class Magic 
{ 
  private $values = [&#39;test&#39; => &#39;value&#39;]; 
 
  public function __get($key) 
  { 
    if (isset($this->values[$key])) { 
      return $this->values[$key]; 
    } 
  } 
}

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

$regular = new Regular(); 
var_dump($regular->test);  // outputs string(4) "value" 
$magic = new Magic(); 
var_dump($magic->test);   // outputs string(4) "value"

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

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

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

结果是不是很意外?

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

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

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

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

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

Statement:
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