I have a class that is basically a wrapper for an array and implements IteratorAggregate. When a new class object is created, it stores it in a protected variable named $ value. The value can be a string, an integer, etc. Or a workaround (like an array).
This object is "recursive" because when the passed object (for example, an array) is passed to the constructor, it creates another instance of the class. Here is the constructor to clarify:
class ListItem implements \IteratorAggregate { protected $readOnly = false; protected $key; protected $value; public function __construct($key, $value, $readOnly = false) { if($readOnly) $this->readOnly = true; if(is_numeric($key)) $key = 'index'.$key; $this->key = $key; if (is_array($value) || $value instanceof Traversable) { $this->value = array(); foreach($value as $k => $v) { if(is_numeric($k)) $k = 'index'.$k; $this->value[$k] = new ListItem($k, $v, $readOnly); } } else { $this->value = $value; } } public function __toString() { if ( is_array($this->value) ) { return 'ListItem OBJECT(' . count($this->value) . ')'; } else { return $this->value; } }
Now I'm trying to write a simple sorting method for a class.
To sort by key, this works like a charm:
$success = ksort($this->value, $comparison);
but for sorting by value, asort does not work, since the actual value that I am trying to sort is stored inside the value property.
So I tried using uasort, for example:
$success = uasort($this->value, function ($a, $b) { if ($a->value == $b->value) return 0; else if($a->value < $b->value) return -1; else return 1; });
but for some reason I get the following error:
Warning: uasort () [function.uasort]: the array has been changed by the user comparison function in /*/*/*/ListItem.php on line 129
Q. Why does this happen if I just access $ value for comparison, without actually changing anything?