为什么这两个对象是相等的(==)?

时间:2011-05-20 23:10:15

标签: php object comparison

在PHP中我有两个对象,它们是不同的,因为$ _frets变量(x是字符串“x”),但PHP说

($o1 == $o2) == TRUE.

为什么?

转储$o1

guitarChord Object
(
    [_guitarChord:guitarChord:private] => 
    [_chord:guitarChord:private] => chord Object()
    [_baseFret:guitarChord:private] => 0
    [_frets:guitarChord:private] => Array
        (
            [0] => x
            [1] => 0
            [2] => 2
            [3] => 2
            [4] => 2
            [5] => x
        )

    [_tuning:guitarChord:private] => tuning Object()
    [currVariation] => 0
    [nextVariation] => 
    [prevVariation] => 
)

转储$o2

guitarChord Object
(
    [_guitarChord:guitarChord:private] => 
    [_chord:guitarChord:private] => chord Object()
    [_baseFret:guitarChord:private] => 0
    [_frets:guitarChord:private] => Array
        (
            [0] => x
            [1] => 0
            [2] => 2
            [3] => 2
            [4] => 2
            [5] => 0
        )

    [_tuning:guitarChord:private] => tuning Object()
    [currVariation] => 0
    [nextVariation] => 
    [prevVariation] => 
)

编辑:

所以原因是因为("x" == 0) = TRUE。谁能告诉我为什么?

1 个答案:

答案 0 :(得分:4)

x表示字符串还是x表示null?如果它表示null,则这是我的理论:Comparison Operators页面具有示例#1中的数组比较算法的转录。基于此,我想在你的情况下,最终会发生什么是0和null之间的比较。根据上表,当null与任何东西比较时,它会转换为bool。因此,您最终将0(false)与null(false)进行比较,从而导致两个数组被视为相等。