markdown 不要使用`empty`进行比较--Potherca在PHP中创建更健壮的代码的规则

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown 不要使用`empty`进行比较--Potherca在PHP中创建更健壮的代码的规则相关的知识,希望对你有一定的参考价值。

<kbd>
    ℹ️ This document is part of 
    <a href="https://gist.github.com/Potherca/9afb08c7cf1beab383564902bbe67be3">
        Potherca's Rules for creating more robust code in PHP
    </a>
</kbd>

# Do not use [`empty`][php-empty] for comparisons

## Description

A developer wants to check that a `$variable` actually contains a value.

The developer does not know (or does not care) what the _exact_ value of the
variable is.

The developer decides to use `empty`.

## Workings

When code contains `if ( ! empty($variable)) { /* ... */}` what actually happens 
is:

```php
if (
    $variable !== ""  // an empty string
    && $variable !== 0   // 0 as an integer
    && $variable !== 0.0 // 0 as a float
    && $variable !== "0" // 0 as a string
    && $variable !== NULL
    && $variable !== FALSE
    && $variable !== array()  // an empty array
    // && ! (variable declared but without a value)
) {
    /* ... */
}
```

Furthermore, `empty()` does _not_ generate a warning if the variable does not exist.

## Rational

The `empty` function incorporates several checks. From the function name it is
not clear what "empty" means. To be certain a developer will have to look the 
exact working up in the manual.

This is a classic case of hidden complexity. The code may _look_ simple but it
is _not_ as simple as it looks. 

## Alternatives

Use a more strict and declarative check. 

## Counter arguments (and response)

- **But now my `if` is verbose and ugly! Using `empty` keeps it short and simple.**  
  To have the check be simple without using `empty` see **[Use function calls in `if` statements]**.

## Relevant rules

- Be explicit
- Do not hide complexity

## Resources

- PHP manual entry on `empty` [http://php.net/manual/en/function.empty.php][php-empty]

[php-empty]: http://php.net/manual/en/function.empty.php

以上是关于markdown 不要使用`empty`进行比较--Potherca在PHP中创建更健壮的代码的规则的主要内容,如果未能解决你的问题,请参考以下文章

Markdown编辑器editormd使用过程中的坑希望你不会遇到

为啥将 var Empty 与零值 var Integer 进行比较时,“=”运算符结果为真?

? | 不要再使用 markdown 主题了!

怎样引导新手使用 Markdown

怎样引导新手使用 Markdown

Markdown 基本语法