Re: Best way of iterating over object member fields?
| From: | Peter Ford | Date: | Wed, 03 Sep 2014 10:19:35 +0000 |
| Subject: | Re: Best way of iterating over object member fields? | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-323809@lists.php.net to get a copy of this message | ||
On 03/09/14 10:34, Stuart Dallas wrote:
On Wednesday, Sep 3, 2014 at 10:23 am, Peter Ford <pete@justcroft.com>, wrote: -Stuart — Stuart Dallas 3ft9 Ltd http://3ft9.com/ I came across a bug in some of my code, where I do something like the following: $obj = new MyObject(); foreach ($obj as $key=>$value) {Thanks Stuart, RTFM works nicely :) Of course, the line gains a bit of weight: foreach (array_keys(get_class_vars('MyObject')) as $key) but at least it clears the hint. -- Peter Ford phone: 01580 893333 fax: 01580 893399 Justcroft International Ltd. www.justcroft.com Justcroft House, High Street, Staplehurst, Kent TN12 0AH United Kingdom Registered in England and Wales: 2297906 Registered office: Stag Gates House, 63/64 The Avenue, Southampton SO17 1XSecho $key;} Note that I don't use $value in the loop - I'm only doing processing based on the field name. Now my IDE flags this unused variable as a hint, so (on autopilot) I changed it to be $obj = new MyObject(); foreach (array_keys($obj) as $key) {echo $key;} Which removes the hint, and looks like the right sort of thing. Of course this doesn't work: "array_keys() expects parameter 1 to be an array, object found". So what is the correct way to list the field names of an object? Two ways depending on whether you want to get them from the class definition or what the object actually contains: * http://php.net/get-class-vars * http://php.net/get-object-vars