Performing an asort on a collection of objects

42 Views Asked by At

Wondering if anybody can help shed any light on what PHP is doing under the hood when performing an asort on a collection of objects.

Take the following snippet:

class NameValuePair
{
    private $name;
    private $value;

    public function __construct($name, $value)
    {
         $this->name = $name;
         $this->value = $value;
    }

    public function getName() { return $this->name; }
    public function getValue() { return $this->value; }
}

$nameValuePairs = [
    new NameValuePair('f', 'f'),
    new NameValuePair('b', 'b'),
    new NameValuePair('z', 'z'),
    new NameValuePair('s', 's')
];

asort($nameValuePairs);

The asort is correctly sorting the array by the $name property of the NameValuePair instances - the resulting array contains objects in the order of bfsz

I have implemented two unit tests - I did not expect the asort to correctly sort the collection and I would always use a usort to sort an array of objects.

Please see this gist for full context and unit tests: https://gist.github.com/mgldev/91386cc6e3d65fc239de60dc1bc46114

General musings

  • Can't find any documentation online about how PHP treats objects within in an array when performing an asort

  • Would have thought the default behaviour would be something along the lines of spl_object_hash and a sort on the hashes

  • Appears to sort using the $name property of the NameValuePair instance, not the $value
  • Is PHP doing something like get_object_vars() to get the object as an array and then sorting on that? get_object_vars would return an empty array on private properties though
  • How is PHP getting to the $name attribute? Why is it picking the $name attribute?
  • Is something else at play here?

Any thoughts?

0

There are 0 best solutions below