2

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.

tereško
  • 58,060
  • 25
  • 98
  • 150
Code4R7
  • 2,600
  • 1
  • 19
  • 42

1 Answers1

2

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

Wax Cage
  • 788
  • 2
  • 8
  • 24
  • By implementing the Iterator interface I technically do not have to use a decorator pattern. But.. to keep track of the information I would have to use an array. While the properties have their own order, which I want to be able to control. – Code4R7 May 26 '17 at 12:00
  • You just need one variable in which you define the order you would like to proceed ($attributeOrder). Then in the next() method you traverse over this array instead and in the current() method return the value of desired attribute (respecting the $attributeOrder). In key() method you define the returned key (again from $attributeOrder) – Wax Cage May 26 '17 at 12:03
  • First comment on the ArrayObject interface: "ArrayObject is not an array so you can't use the built in array functions". ArrayAccess is part of ArrayObject, which makes me wonder how to control the actual order of the object properties. How would I insert `$o->ah = 1.5;` between properties `$a` and `$b`, without reverting to arrays? – Code4R7 May 26 '17 at 12:24
  • It looks like changing the order of the properties [can not be done](https://stackoverflow.com/questions/24899978/add-property-to-stdclass-at-the-top-of-the-object-in-php). So there is no use case.. :-) Implementing the ArrayObject interface is the next best thing. Thanks! – Code4R7 May 26 '17 at 17:56
  • Its really logical - object attributes are inner programming structure used for purposes of programming language. If you want any kind of printing/viewing or even ordered iteration over attributes, you should use some business layer (mapper, view, ...) to wrap it into. – Wax Cage May 29 '17 at 08:54