Inverted Spaceship Results

<?php

class A {
    public string $a;
    public string $b;
    public function __construct(
        string $a,
        string $b,
    ){
        $this->a = $a;
        $this->b = $b;
    }
}

$a = new A('b', 'a');
$b = new A('a', 'b');

var_dump($a <=> $b);  // 1
var_dump($b <=> $a);  // -1

class B {
    public string $b;  // The property declarations are inverted
    public string $a;
    public function __construct(
        string $a,
        string $b,
    ){
        $this->a = $a;
        $this->b = $b;
    }
}

$a = new B('b', 'a');
$b = new B('a', 'b');

var_dump($a <=> $b);  // -1
var_dump($b <=> $a);  // 1

In the first class, the properties are declared $a, then $b. Comparing the values with spaceship leads to 1, -1.

In the first class, the properties are declared $b, then $a. The rest of the code is the same. Comparing the values with spaceship leads to -1, 1.

This phenomenon disappears when using promoted properties.

See Also

PHP Features

Last updated: 14 July 2026