Re: Object to array conversion oddity

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

 



Marcus Bointon wrote:
Sure, but don't you think that coding should at least try to be driven by logic rather than luck? I'm also not denying that it's not too hard to work around (with a function not dissimilar to what you suggested), but I'd really prefer it if it just did what it says on the tin. By its very nature, casting from object to array indicates that you no longer want the constraints of property protection, which an array can't preserve anyway, and it's not as if there are not intentional, documented methods of obtaining this information.
Along those lines, I think that logically, if you were to cast an Object to an array, it should only export the public properties. Since the private/protected properties aren't visible outside the class, it would be safe to assume that they're not for public consumption. After all, they're intended (by design of the class) only to be accessed via functions defined in the class. I think PHP's behavior is a bit odd, but still somewhat logical.

If you just want an array of properties, add this to your class.

       public function getPropertyArray() {
               $refClass  = new ReflectionClass(__CLASS__);
               $properties = $refClass->getProperties();

               $propArray = Array();
               foreach ($properties as $property) {
                       if (!$property->isStatic()) {
                               $name = $property->getName();
                               $propArray[$name] = $this->$name;
                       }
               }
               return($propArray);
       }

And that'll do essentially what you're asking for. You could just call it toArray() too, and even check for isPublic/isPrivate/isProtected for some additional granularity.

jon

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[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