PHP:编写严格的代码有什么好处吗?

问题描述:

When I set error_reporting(E_ALL | E_STRICT);, my code produces Undefined variable errors. I can solve them, but I am wondering whether there is any difference in speed or memory usage between writing code that passes strict checks, and just turning E_STRICT off?

当我设置 error_reporting(E_ALL | E_STRICT); code>时,我的代码生成 未定义的变量 code>错误。 我可以解决它们,但是我想知道在编写通过严格检查的代码和只是关闭 E_STRICT code>之间在速度或内存使用方面是否存在任何差异? p> div>

There is no mechanical benefit. You are, however, protected from doing really common, really dumb things like not always initializing a variable before using it - because with E_STRICT on, PHP will generate an error instead of allowing functions to break in potentially-catastrophic, and probably-invisible ways.

For example, it's completely conceivable that a database-backed application uses a variable that isn't initialized by all possible execution paths:

// Adds an allergy to the user's records
public function Add($AllergyID) {
    $Patient = $this->Patient->Load();

    if ($Patient->Insurance->StartDate < now()) {
          $Allergies = $Patient->Allergies->Get();
          $Allergies[] = $AllergyID;
    }

    $Patient->Allergies->Set($Allergies);
}

Eventually it doesn't get initialized, and somebody's medical records table is silently truncated.

In short, you should always develop with all warnings: it's your first line of defense. When it comes time to move your code into production, though, you absolutely want error reporting off. You don't want malicious users gaining insight into the inner workings of your application, or - worse - your database.

less errors result in better speed; maintainability will be incresed; memory enhancement maybe too, because of log won't be flus

There is NO speed Benefit, but while using PHP 5.2.0. or before you should use E_ALL | E_STRICT for the development purposes.

But for the PHP 5.2.0 above E_STRICT is included in the E_ALL itself.

Or you can use error_reporting(-1); Which will always include everything, even if they are present in E_ALL.

use the below * question for further reference What is the recommended error_reporting() setting for development? What about E_STRICT?