PHP: change order of object properties

点点圈 提交于 2021-02-10 06:09:39

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/44200772/php-change-order-of-object-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!