# Proposal for a RFC

- Thread: https://externals.io/message/105589
- Original archive: https://news-web.php.net/php.internals/105589
- Started by Steven Wade on 2019-05-04T14:58:41+00:00
- Messages: 33
- RFC: __toArray() (Inactive) — https://externals.io/rfc/to-array.md
- Page 1 of 2: messages 1 to 25 (25 per page, add `?page=N` to the URL)
- Next page: https://externals.io/message/105589.md?page=2
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · RFCs at https://externals.io/rfc.md · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #105589 — Steven Wade — 2019-05-04T14:58:41+00:00

URL: https://externals.io/message/105589#105589

Hi Internals team!

I have an idea for a feature that I'd love to see in the language one day and wanted to run the idea by you all. 

The idea is to add a new magic method "__toArray()" that would allow a developer to specifiy how a class is cast to an array. The idea is the same mentality of __toString(), but, for arrays.

I would personally love this feature and those I've run it by were also excited by the idea. So I'm soliciting feedback in hopes that things go well and I can officially write the RFC. As for implementation, Sara Golemon is awesome and while chatting a few months back, knocked out a proof-of-concept implementation <https://github.com/sgolemon/php-src/tree/experimental.toarray>.  There's still work to be done if this proposal gets to the RFC phase, but again, just gauging interest here.

I appreciate any feedback you all can provide.

Thanks,

- Steven Wade

---

## #105590 — Paul Jones — 2019-05-04T15:59:46+00:00

URL: https://externals.io/message/105589#105590

Hi Steven,

> The idea is to add a new magic method "__toArray()" that would allow a developer to specifiy how a class is cast to an array. The idea is the same mentality of __toString(), but, for arrays.

I'd like to see this as well.


-- 
Paul M. Jones
pmjones@pmjones.io
http://paul-m-jones.com

Modernizing Legacy Applications in PHP
https://leanpub.com/mlaphp

Solving the N+1 Problem in PHP
https://leanpub.com/sn1php

---

## #105591 — Kalle Sommer Nielsen — 2019-05-04T16:08:15+00:00

URL: https://externals.io/message/105589#105591

Hi

Den lør. 4. maj 2019 kl. 17.58 skrev Steven Wade <stevenwadejr@gmail.com>:
>
> Hi Internals team!
>
> I have an idea for a feature that I'd love to see in the language one day and wanted to run the idea by you all.
>
> The idea is to add a new magic method "__toArray()" that would allow a developer to specifiy how a class is cast to an array. The idea is the same mentality of __toString(), but, for arrays.

While this sounds great and all, I do wonder about the implications it
may have on the already existing behavior of type casting an object
into an array which returns current public/protected/private property
values. While this functionality is not an ideal or by design, it is
fairly heavily (ab-)used, meaning that it is a potential BC break
without the ability to an alternative.

See this example: https://3v4l.org/ONMoi

-- 
regards,

Kalle Sommer Nielsen
kalle@php.net

---

## #105592 — Paul Jones — 2019-05-04T16:10:45+00:00

URL: https://externals.io/message/105589#105592

> 
> 
> Hi
> 
> Den lør. 4. maj 2019 kl. 17.58 skrev Steven Wade <stevenwadejr@gmail.com>:
> > […]
> 
> While this sounds great and all, I do wonder about the implications it
> may have on the already existing behavior of type casting an object
> into an array which returns current public/protected/private property
> values.

I find it easy to imagine that objects not implementing __toArray() would continue to exhibit that behavior.


-- 
Paul M. Jones
pmjones@pmjones.io
http://paul-m-jones.com

Modernizing Legacy Applications in PHP
https://leanpub.com/mlaphp

Solving the N+1 Problem in PHP
https://leanpub.com/sn1php

---

## #105593 — Kalle Sommer Nielsen — 2019-05-04T16:11:23+00:00

URL: https://externals.io/message/105589#105593

> I find it easy to imagine that objects not implementing __toArray() would continue to exhibit that behavior.

Obviously. So what about code that operates on this behavior, should
that then suddenly break if the object implements an __toArray()
method? That sounds wrong to me


-- 
regards,

Kalle Sommer Nielsen
kalle@php.net

---

## #105594 — Marco Pivetta — 2019-05-04T16:36:43+00:00

URL: https://externals.io/message/105589#105594

Hi Steven,

As it currently stands, the array cast is the only operation capable of
exposing object state without triggering any kind of access guards: it is
very much required for anything that works with reflection and typed
properties, and possibly the only operation in PHP that operates on state
without some contraption intercepting its execution.

It is also necessary to distinguish dynamic properties from declared object
state.

For comparison, all of the following have side-effects due to the
complexity of the language:

 * isset()
 * unset()
 * property read
 * property write
 * ReflectionProperty#getValue()
 * ReflectionProperty#setValue()

Overall, this is problematic, and introduces more magic that I'd gladly
avoid, in an endpoint used to work around all the engine magic (the only
stable one so far).

From my end, this sounds like a bad idea, because it removes one of the
very very few referentially transparent guarantees (if not the only one,
when dealing with objects) from the language.

Greets,

Marco



> Hi Internals team!
>
> I have an idea for a feature that I'd love to see in the language one day
> and wanted to run the idea by you all.
>
> The idea is to add a new magic method "__toArray()" that would allow a
> developer to specifiy how a class is cast to an array. The idea is the same
> mentality of __toString(), but, for arrays.
>
> I would personally love this feature and those I've run it by were also
> excited by the idea. So I'm soliciting feedback in hopes that things go
> well and I can officially write the RFC. As for implementation, Sara
> Golemon is awesome and while chatting a few months back, knocked out a
> proof-of-concept implementation <
> https://github.com/sgolemon/php-src/tree/experimental.toarray>.  There's
> still work to be done if this proposal gets to the RFC phase, but again,
> just gauging interest here.
>
> I appreciate any feedback you all can provide.
>
> Thanks,
>
> - Steven Wade

---

## #105595 — Mark Randall — 2019-05-04T18:12:35+00:00

URL: https://externals.io/message/105589#105595

> The idea is to add a new magic method "__toArray()" that would allow a developer to specifiy how a class is cast to an array. The idea is the same mentality of __toString(), but, for arrays.

I see possibilities for it, and on a slightly wider approach, I do think 
it would be nice if PHP could eventually have full operator overloading.

It goes against my better judgement for enforcing return types, but 
maybe a generic __cast function taking a single argument of the desired 
type might be an option.

The engine could enforce the return type being the same as the argument 
type, and the main IDE tools in use support metadata patterns to perform 
static analysis.

Question is, would it be either a supports/cast function pair, an 
exception thrower, or something else...

class X {
    /* ... */

    public function __cast($type) {
       if ($type === 'array') {
          return (array)$this;
       }

       if ($type === MyObject::class) {
          return new MyObject($this->x, $this->y);
       }

       throw new InvalidCastError($type);
    }

    public function __castable(): array {
       return [ 'array', MyObject::class ];
    }
}

Eh, my suggestion is probably a terrible ideal.

--
Mark Randall

---

## #105596 — Ben Ramsey — 2019-05-05T14:59:57+00:00

URL: https://externals.io/message/105589#105596

> 
> 
> Hi Internals team!
> 
> I have an idea for a feature that I'd love to see in the language one day and wanted to run the idea by you all. 
> 
> The idea is to add a new magic method "__toArray()" that would allow a developer to specifiy how a class is cast to an array. The idea is the same mentality of __toString(), but, for arrays.
> 
> I would personally love this feature and those I've run it by were also excited by the idea. So I'm soliciting feedback in hopes that things go well and I can officially write the RFC. As for implementation, Sara Golemon is awesome and while chatting a few months back, knocked out a proof-of-concept implementation <https://github.com/sgolemon/php-src/tree/experimental.toarray>.  There's still work to be done if this proposal gets to the RFC phase, but again, just gauging interest here.
> 
> I appreciate any feedback you all can provide.
> 
> Thanks,
> 
> - Steven Wade

Using existing language functionality, would it satisfy the similar needs if you implement IteratorAggregate and return an ArrayIterator from the getIterator() method? Obviously, the (array) cast wouldn’t use this, but you could do $object->getIterator()->getArrayCopy().

I’m not against the proposal. I’m mainly asking if there are other ways in the language today to accomplish similar things. I would prefer to see interfaces used over more magic methods (something like ArraySerializable).

-Ben

---

## #105597 — Nicolas Grekas — 2019-05-05T15:07:43+00:00

URL: https://externals.io/message/105589#105597

Le sam. 4 mai 2019 à 18:37, Marco Pivetta <ocramius@gmail.com> a écrit :

> Hi Steven,
>
> As it currently stands, the array cast is the only operation capable of
> exposing object state without triggering any kind of access guards: it is
> very much required for anything that works with reflection and typed
> properties, and possibly the only operation in PHP that operates on state
> without some contraption intercepting its execution.
>
> It is also necessary to distinguish dynamic properties from declared object
> state.
>
> For comparison, all of the following have side-effects due to the
> complexity of the language:
>
>  * isset()
>  * unset()
>  * property read
>  * property write
>  * ReflectionProperty#getValue()
>  * ReflectionProperty#setValue()
>
> Overall, this is problematic, and introduces more magic that I'd gladly
> avoid, in an endpoint used to work around all the engine magic (the only
> stable one so far).
>
> From my end, this sounds like a bad idea, because it removes one of the
> very very few referentially transparent guarantees (if not the only one,
> when dealing with objects) from the language.
>
> Greets,
>
> Marco
>

I want to weight in with what Marco expressed. I have the very same
concerns and they are major ones for many use cases. Mine is VarDumper.

Please don't do this the way it is described.

Nicolas

---

## #105598 — Steven Wade — 2019-05-06T14:37:24+00:00

URL: https://externals.io/message/105589#105598

> 
> 
> 
> > […]
> 
> Using existing language functionality, would it satisfy the similar needs if you implement IteratorAggregate and return an ArrayIterator from the getIterator() method? Obviously, the (array) cast wouldn’t use this, but you could do $object->getIterator()->getArrayCopy().
> 
> I’m not against the proposal. I’m mainly asking if there are other ways in the language today to accomplish similar things. I would prefer to see interfaces used over more magic methods (something like ArraySerializable).

PHP already has the magic built in. The proposal is really just a way to control the magic. We already have "(string) $foo" and "__toString()", so the idea of implementing a "__toArray()" method is bringing a feature more inline with what's already there. 

I think it reads easier and cleaner "(array) $foo", and a simpler as a developer to implement than a mix of chained methods and interfaces.

That being said, adding an interface like `ArraySerializable` might be nice too. I'm seeing technical arguments against adding magic casts, but (just spit-balling here), what if a class implemented a new `ArraySerializable` interace with whatever method it demands, and if that is attempted to be cast to an array either manually by calling "(array) $foo" or PHP attempting to, then the array serialize method is called. ¯\_(ツ)_/¯

---

## #105599 — Ben Ramsey — 2019-05-06T14:45:04+00:00

URL: https://externals.io/message/105589#105599

> 
> 
> That being said, adding an interface like `ArraySerializable` might be nice too. I'm seeing technical arguments against adding magic casts, but (just spit-balling here), what if a class implemented a new `ArraySerializable` interace with whatever method it demands, and if that is attempted to be cast to an array either manually by calling "(array) $foo" or PHP attempting to, then the array serialize method is called. ¯\_(ツ)_/¯

That’s how I would prefer to see it work.

BTW, I’m not suggesting `ArraySerializable` as the name. I used that to make a connection to `JsonSerializable`, which I think did a good job of using an interface for this kind of thing (even though it’s not quite the same because there’s no cast for a JSON type).

In some of my open source projects, I’ve had to add `__toString()` to the interfaces to ensure that implementers implement it. It would be nice for my interfaces to instead extend an internal interface like `Stringable`.

-Ben

---

## #105614 — Steven Wade — 2019-05-07T12:19:44+00:00

URL: https://externals.io/message/105589#105614

> I want to weight in with what Marco expressed. I have the very same concerns and they are major ones for many use cases. Mine is VarDumper.
> 
> Please don't do this the way it is described.


Is there a way that you'd suggest? First of all, TIL some cool things about "(array) $foo" and how VarDumper uses that, so thank you! Secondly, I believe the casting syntax is the best user experience and would be a good addition to the language, so is there any other way at all to maintain something like VarDumper's functionality without using the casting syntax? I'd like to find a way to not distrupt too much of what's out there, while also adding value to the end user.

--
Steven Wade
stevenwadejr@gmail.com

---

## #105615 — Nikita Popov — 2019-05-07T12:22:14+00:00

URL: https://externals.io/message/105589#105615

> > […]
> concerns and they are major ones for many use cases. Mine is VarDumper.
> > […]
>
>
> Is there a way that you'd suggest? First of all, TIL some cool things
> about "(array) $foo" and how VarDumper uses that, so thank you! Secondly, I
> believe the casting syntax is the best user experience and would be a good
> addition to the language, so is there any other way at all to maintain
> something like VarDumper's functionality without using the casting syntax?
> I'd like to find a way to not distrupt too much of what's out there, while
> also adding value to the end user.
>

We can add a separate function to provide this functionality. We should do
that anyway because it's both clearer and because (array) already requires
some special handling for ArrayObject that could be avoided.

Nikita



> > […]
> concerns and they are major ones for many use cases. Mine is VarDumper.
> > […]
>
>
> Is there a way that you'd suggest? First of all, TIL some cool things
> about "(array) $foo" and how VarDumper uses that, so thank you! Secondly, I
> believe the casting syntax is the best user experience and would be a good
> addition to the language, so is there any other way at all to maintain
> something like VarDumper's functionality without using the casting syntax?
> I'd like to find a way to not distrupt too much of what's out there, while
> also adding value to the end user.
>
> --
> Steven Wade
> stevenwadejr@gmail.com

---

## #105616 — Steven Wade — 2019-05-07T12:25:06+00:00

URL: https://externals.io/message/105589#105616

> I’m not against the proposal. I’m mainly asking if there are other ways in the language today to accomplish similar things. I would prefer to see interfaces used over more magic methods (something like ArraySerializable).

A Twitter user pointed out that 7.4 is adding two new magic methods <https://wiki.php.net/rfc/custom_object_serialization> - __serialize() and __unserialize(). So adding more magic methods to PHP isn't unprecedented. 

On the same note, casting is already magical, so controling the implementation via a magic method is more in line with current functionality.

--
Steven Wade
stevenwadejr@gmail.com

---

## #105617 — Steven Wade — 2019-05-07T12:28:14+00:00

URL: https://externals.io/message/105589#105617

> We can add a separate function to provide this functionality. We should do that anyway because it's both clearer and because (array) already requires some special handling for ArrayObject that could be avoided.


Are you talking about adding a separate function to replace my proposed __toArray() and casting functionality? Or did you mean adding a separate function to add functionality and insight into objects that packages like VarDumper have been using casting to access?

--
Steven Wade
stevenwadejr@gmail.com

---

## #105618 — Stephen Reay — 2019-05-07T12:31:53+00:00

URL: https://externals.io/message/105589#105618

> 
> 
> 
> 
> > […]
> 
> We can add a separate function to provide this functionality. We should do
> that anyway because it's both clearer and because (array) already requires
> some special handling for ArrayObject that could be avoided.
> 
> Nikita
> 
> 
> 
> > […]

Maybe I’m missing the point (I’ve never used it) of VarDumper, but isn’t this type of thing exactly why the `__debugInfo` magic method exists?

---

## #105619 — Steven Wade — 2019-05-07T12:47:41+00:00

URL: https://externals.io/message/105589#105619

> Maybe I’m missing the point (I’ve never used it) of VarDumper, but isn’t this type of thing exactly why the `__debugInfo` magic method exists?


I can't speak for the exact reason a library like VarDumper is using casting versus __debugInfo, but in trying to find a substitute this morning, I played with the method you mentioned and found that it can be overwritten by classes and be commanded to not return anything (similar to my __toArray proposal), whereas current functionality prevents overriding casting to an array so casting will always give you insight but users can overwrite __debugInfo and cause unintended effects. I assume that's the reason for not using __debugInfo.

--
Steven Wade
stevenwadejr@gmail.com

---

## #105620 — Stephen Reay — 2019-05-07T12:52:58+00:00

URL: https://externals.io/message/105589#105620

> 
> 
> > […]
> 
> 
> I can't speak for the exact reason a library like VarDumper is using casting versus __debugInfo, but in trying to find a substitute this morning, I played with the method you mentioned and found that it can be overwritten by classes and be commanded to not return anything (similar to my __toArray proposal), whereas current functionality prevents overriding casting to an array so casting will always give you insight but users can overwrite __debugInfo and cause unintended effects. I assume that's the reason for not using __debugInfo.
> 
> --
> Steven Wade
> stevenwadejr@gmail.com
> 
> 
> 

Right, I understand that it *can* be overridden, but surely if someone’s doing that, its because they want more useful information provided in, e.g. var_dump.

---

## #105621 — Steven Wade — 2019-05-07T12:57:49+00:00

URL: https://externals.io/message/105589#105621

> 
> 
> 
> > […]
> 
> Right, I understand that it *can* be overridden, but surely if someone’s doing that, its because they want more useful information provided in, e.g. var_dump.


I think that's a good point. If we follow that mentality, then the proposed __toArray and it's subsequent ability to affect array casting isn't a worry too much as the proposal is to only call __toArray if it exists and an object is cast to an array, so if a user manually implements __toArray, then we could assume "they want more useful information provided in, e.g. var_dump."

--
Steven Wade
stevenwadejr@gmail.com

---

## #105622 — Marco Pivetta — 2019-05-07T12:58:20+00:00

URL: https://externals.io/message/105589#105622

Hey Steven,




> > […]
> in the language today to accomplish similar things. I would prefer to see
> interfaces used over more magic methods (something like ArraySerializable).
>
> A Twitter user pointed out that 7.4 is adding two new magic methods <
> https://wiki.php.net/rfc/custom_object_serialization> - __serialize() and
> __unserialize(). So adding more magic methods to PHP isn't unprecedented.
>
> On the same note, casting is already magical, so controling the
> implementation via a magic method is more in line with current
> functionality.
>

With your current proposal so far, I'd simply have to throw an exception:
`if (method_exists($object, '__toArray')) { throw
UnsupportedObject::from($object); }`

The alternative is to expand the reflection API with an array cast
operation in there, and then migrate existing userland usages to that to
retain BC.

In addition to that, as someone that used to write a lot of `__toString()`
(and now doesn't do that anymore), a clear API and interfaced (non-magic)
`toArray()` is more powerful and useful.

Greets,

Marco

---

## #105623 — Steven Wade — 2019-05-07T13:08:26+00:00

URL: https://externals.io/message/105589#105623

Hi Marco,

> The alternative is to expand the reflection API with an array cast operation in there, and then migrate existing userland usages to that to retain BC.

That's an interesting proposal - adding new reflection abilities. Hm..

> In addition to that, as someone that used to write a lot of `__toString()` (and now doesn't do that anymore), a clear API and interfaced (non-magic) `toArray()` is more powerful and useful.


I see you and I hear you. After 12 years, still like the magic of PHP. I like that casting is quick, simple, and is less verbose when writing/reading. But I'm not opposed to further discussing possible solutions. If this gets to the RFC stage, I'd prefer it be the best option for the language and most likely to pass.

--
Steven Wade
stevenwadejr@gmail.com

---

## #105642 — Steven Wade — 2019-05-08T14:13:29+00:00

URL: https://externals.io/message/105589#105642

Hi Kalle,

> 
> 
> Hi
> 
> Den lør. 4. maj 2019 kl. 17.58 skrev Steven Wade <stevenwadejr@gmail.com>:
> > […]
> 
> While this sounds great and all, I do wonder about the implications it
> may have on the already existing behavior of type casting an object
> into an array which returns current public/protected/private property
> values. While this functionality is not an ideal or by design, it is
> fairly heavily (ab-)used, meaning that it is a potential BC break
> without the ability to an alternative.
> 
> See this example: https://3v4l.org/ONMoi <https://3v4l.org/ONMoi>

That's a great example, thanks for that. I can understand how casting now can be as you say "abused". With my proposal, the default behavior wouldn't change unless someone implemented the __toArray() method on their class, which would simply give them greater control over how that class is represented.

In regards to the output of the example you linked, the same is possible today with reflection: https://3v4l.org/Ab51l <https://3v4l.org/Ab51l>

If libraries are using casting to gain insight into objects, it seems that they could be updated to use reflection without losing any functionality.

--
Regards,

Steven Wade
stevenwadejr@gmail.com

---

## #105686 — Steven Wade — 2019-05-13T13:46:36+00:00

URL: https://externals.io/message/105589#105686

> 
> 
> Hi Internals team!
> 
> I have an idea for a feature that I'd love to see in the language one day and wanted to run the idea by you all. 
> 
> The idea is to add a new magic method "__toArray()" that would allow a developer to specifiy how a class is cast to an array. The idea is the same mentality of __toString(), but, for arrays.
> 
> I would personally love this feature and those I've run it by were also excited by the idea. So I'm soliciting feedback in hopes that things go well and I can officially write the RFC. As for implementation, Sara Golemon is awesome and while chatting a few months back, knocked out a proof-of-concept implementation <https://github.com/sgolemon/php-src/tree/experimental.toarray>.  There's still work to be done if this proposal gets to the RFC phase, but again, just gauging interest here.
> 
> I appreciate any feedback you all can provide.
> 
> Thanks,
> 
> - Steven Wade

Hi all, I wanted to re-ping the list to see if there is any more feedback on this proposal? Any technical concerns or true BC changes?

This feature wouldn't be as exciting as the others in 7.4, but I think it'd be a nice little helper, and the community feedback I've received from developers has been positive, so I'd like to keep the conversation going.

--
Steven Wade
stevenwadejr@gmail.com

---

## #105688 — Rowan Collins — 2019-05-13T14:17:28+00:00

URL: https://externals.io/message/105589#105688

>
> Hi all, I wanted to re-ping the list to see if there is any more feedback
> on this proposal? Any technical concerns or true BC changes?
>


I'm personally unconvinced of the value of this, and would probably propose
it was blocked by coding standards in my team if it was added, because its
meaning is so ambiguous.

I actually see quite a lot of classes with normal methods called things
like "toArray", and my comment is always "to *what* array?" Most objects do
not have a single "natural"/"canonical" array representation, and such a
transform is usually actually used as part of some particular helper or
code pattern - e.g. an intermediate form for serializing to XML/JSON, or a
compatibility-wrapper for legacy code. There's nearly always a better name
for the method that properly indicates its intent.

As a thought experiment, imagine a similar method which allowed you to
overload (object)$foo. Although (array)$foo tells you slightly more than
that, I'm not convinced it tells you enough that you're not just hiding
meaning behind cute syntax.

JsonSerializable actually suffers from similar problems, and is IMO useful
only because it's automatically recursive. I presume the proposed mechanism
would not be, i.e. return [$foo] would not be interpreted as return
[(array)$foo].

Regards,
-- 
Rowan Collins
[IMSoP]

---

## #105690 — Marco Pivetta — 2019-05-13T17:51:40+00:00

URL: https://externals.io/message/105589#105690

Hi Steven,



> > […]
> day and wanted to run the idea by you all.
> > […]
> developer to specifiy how a class is cast to an array. The idea is the same
> mentality of __toString(), but, for arrays.
> > […]
> excited by the idea. So I'm soliciting feedback in hopes that things go
> well and I can officially write the RFC. As for implementation, Sara
> Golemon is awesome and while chatting a few months back, knocked out a
> proof-of-concept implementation <
> https://github.com/sgolemon/php-src/tree/experimental.toarray>.  There's
> still work to be done if this proposal gets to the RFC phase, but again,
> just gauging interest here.
> > […]
>
> Hi all, I wanted to re-ping the list to see if there is any more feedback
> on this proposal? Any technical concerns or true BC changes?
>
> This feature wouldn't be as exciting as the others in 7.4, but I think
> it'd be a nice little helper, and the community feedback I've received from
> developers has been positive, so I'd like to keep the conversation going.
>

I don't think any of the discussion points mentioned above is resolved: a
heavy BC break on the `(array)` cast instead of introducing a clear
`SomeArrayableInterfaceType#toArray()` (to be explicitly called) is a no-go
from my end, as no clear value is added besides more language complexity,
and more mixed cast is encouraged.

Greets,

Marco

---

Next page: https://externals.io/message/105589.md?page=2
