Frankly, a magic method sounds like a much better solution than
auto-magically converting objects to arrays.

The problem with automatic conversion, is that the order of properties is
an implementation detail - the vsprintf() example perfectly illustrates the
problem:

class User
{
    public $first = 'Joe';
    public $last = 'Shmoe';
}

$user = new User;

echo vsprintf('Welcome, %s %s !', $user);


Refactor as follows:

class User
{
    public $age = 37;
    public $first = 'Joe';
    public $last = 'Shmoe';
}


"Welcome, 37 Joe !"

The fact that somebody even came up with the vsprintf() example is scary.

I'm not going to get into how this gets worse when things like inheritance
further makes the order unpredictable.

There is likely only one valid use-case for this, which is converting an
object to an array for the purpose of serialization or other rare cases of
iterating over properties - but we can already handle that with an array()
typecast, yes?

At least the explicitness of the typecast provides some indication of what
you're doing or what to expect.

Magically converting for that one use-case is like an invitation to create
ugly, obscure, unreadable code. (and make mistakes.)

Name a good, valid use-case for this feature ?

On Wed, Apr 24, 2013 at 12:39 PM, Anthony Ferrara <ircmax...@gmail.com>wrote:

> Richard,
>
>
> Oh! Another magic method opportunity ...
>>
>> /**
>>  * Operates just like __toString(), but returns an array.
>>  */
>> public function __toArray();
>>
>>
>> (ducking)
>
>
> I know you're joking, but this has been brought up before (and I intend to
> bring it up again): https://wiki.php.net/rfc/object_cast_to_types
>
>

Reply via email to