Should I be using assert in my PHP code?

前端 未结 8 1565
执念已碎
执念已碎 2020-12-02 16:07

A coworker has added the assert command a few times within our libraries in places where I would have used an if statement and thrown an exception. (I had never even heard o

8条回答
  •  孤城傲影
    2020-12-02 17:06

    An important note concerning assert in PHP earlier than 7. Unlike other languages with an assert construct, PHP doesn't throw assert statements out entirely - it treats it as a function (do a debug_backtrace() in a function called by an assertion). Turning asserts off seems to just hotwire the function into doing nothing in the engine. Note that PHP 7 can be made to emulate this behavior by setting zend.assertions to 0 instead of the more normal values of 1 (on) or -1 (off).

    The problem arises in that assert will take any argument - but if the argument is not a string then assert gets the results of the expression whether assert is on or off. You can verify this with the following code block.

    Given the intent of assert this is a bug, and a long standing one since it's been in the language since assert was introduced back in PHP 4.

    Strings passed to assert are eval'ed, with all the performance implications and hazards that come with that, but it is the only way to get assert statements to work the way they should in PHP (This behavior deprecated in PHP 7.2).

    EDIT: Changed above to note changes in PHP 7 and 7.2

提交回复
热议问题