Type casting and Comparison with Loose Operator “==”

前端 未结 7 2273
暖寄归人
暖寄归人 2020-12-10 16:58

I have a problem baffling me terribly. I noticed this before but didn\'t give it any heed until today. I was trying to write my own check for integer strings. I know of

相关标签:
7条回答
  • 2020-12-10 17:28

    Note: This answer is in response to a related question about the Twig template engine, that was marked as a duplicate, and redirects here.

    Because the context is different, this answer is provided to those members of the SO community who may benefit from additional details specifically related to twig exclusively.

    TL;DR: see this post How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

    Problem

    Context

    • Twig template engine (latest version as of Fri 2017-01-27T05:12:25)

    Scenario

    • DeveloperYlohEnrohK uses comparison operator in twig expression
    • DeveloperYlohEnrohK notices unexpected results when using equality comparison operator

    Questions

    • Why does the equality comparison operator (==) produce unexpected results in Twig?
    • Why do the following produce different results?

      {{ dump(0 == 'somekey') }}          ==> true
      {{ dump(0|lower == 'somekey') }}    ==> false
      

    Solution

    • Since Twig is based on PHP, the casting, implicit type-conversion and comparison semantics of PHP apply to Twig templates as well.
    • Unless DeveloperYlohEnrohK is intentionally and specifically leveraging the behavior of implicit type-conversion in PHP, the comparison expression will almost certainly produce counterintuitive and unexpected results.
    • This is a well-known circumstance that is described in detail in this SO post on PHP equality.
    • Solution: Just as is the case with standard PHP, unless the well-known circumstance is accounted for, using === in Twig is much less likely to produce unexpected results.

    Pitfalls

    • As of this writing, the Twig template engine does not support === in the same way as standard PHP
    • Twig does have a substitute for === using same as
    • Because of this, the treatment of this well-known circumstance differs slightly between PHP and Twig.

    See also

    • How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?
    • http://twig.sensiolabs.org/doc/2.x/tests/sameas.html
    0 讨论(0)
提交回复
热议问题