Re: Best way of iterating over object member fields?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Wed, Sep 3, 2014 at 3:19 AM, Peter Ford <pete@xxxxxxxxxxxxx> wrote:

> 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.


Keep in mind that hints are just that: hints that perhaps you may simplify
the code or improve performance by removing an operation that produces a
value that's never used. Iterating over the keys and values of an object is
an O(n) operation. Building an array of key/value mappings from an object's
properties is an O(n) operation. And building another array holding just
the keys (as values) is yet another O(n) operation.

Thus, to remove a squiggly line under the $value variable in your IDE,
you've turned an O(n) operation into an O(3n) operation. Granted, O(3n) is
still O(n), but clearly it will take roughly three times as long.* And
consider what happens when transforming the object to an array of
key/values to an array of keys. Note that the values are accessed, packaged
up into an array, and then tossed away. That's no different from ignoring
the value in the loop.

Moving from performance to simplicity of design, I find this form more
complicated. You must recognize (or look up) the two functions to see
what's happening. But the simpler loop over the object with an underlined
$value is immediately obvious: you're looping over the object's properties
and ignoring the values.

I would revert to your original form and possibly file a feature request to
support using $ without a name to indicate a throwaway variable that should
not receive a value (similar to _ in Python, though I believe that is an
actual variable and _ is used as a convention to indicate "I don't care
about this value").

    foreach ($object as $key => $)

This would come in handy in other cases where you want to ignore values:

    list($, $author, $name) = explode(',', '123,Charles Lutwidge
Dodgson,Alice in Wonderland');

Cheers,
David

* Of course, array_keys and get_class_vars are internal functions and will
execute faster than iteration over the resulting array or object in PHP
code.

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux