Search code examples
phpobject-properties

PHP: change order of object properties


Regarding PHP, is there a way to change the order of object properties?

class o {public $a = 1, $b = 2;}
$o = new o;
foreach (get_object_vars($o) as $k => $v) {
  print $k . '->' . $v . PHP_EOL;
}

Output:

a->1
b->2

Existing public variables can be unset(), and added e.g. with $o->c = 3;. But array functions do not work with objects, and I do not want to convert the object to some stdClass.

The only practical workaround I can think of is to decorate an array object and overload the magic __get() and __set() methods, but that is just a workaround, not a solution.


Solution

  • You can implement your own way to iterate over object just by implementing Iterator interface. By implementing methods next and current you define how to get current element and how to get the next one (but you will have to implement all methods).

    For iteration use

    foreach ($o as $k => $v) {
      print $k . '->' . $v . PHP_EOL;
    }
    

    Care to see some example? Did you understand it from link above?

    On the other hand if you want to use your object as array, check ArrayObject interface or for simplier use ArrayAccess interface