# What about a magic __toArray() method?

- Thread: https://externals.io/message/108351
- Original archive: https://news-web.php.net/php.internals/108351
- Started by mtkocak@gmail.com on 2020-02-04T07:15:27+00:00
- Messages: 13
- 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

---

## #108351 — mtkocak@gmail.com — 2020-02-04T07:15:27+00:00

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

As you know we have __toString method that runs whenever an object is
typecasted to string or it is directly echoed.

<?php

$class = (new class{
  public function __toString(){
    echo "casted\n";
    return "mahmut\n";
  }
});

echo $class;
$casted = (string)$class;

/*
prints:
casted
mahmut
casted
mahmut
*/


As you know toArray() method implemented when an object is converted into
and array and most of the time when a plain data object is sent to
front-end.

Having a magic method like __toString called __toArray would be useful to
detect and act on conversion events.

Roughly it would be like:

<?php

$class = (new class{
  public function __toArray(){
    echo "casted\n";
    return
    [
      'key'=>'value'
    ];
  }
});


$casted = (array)$class;
print_r($casted);

/*
prints:
Array
(
    [key] => value
)
mahmut
*/

What would you think? I think it would add value.

---

## #108352 — mtkocak@gmail.com — 2020-02-04T07:18:10+00:00

URL: https://externals.io/message/108351#108352 · In reply to: #108351

Or we can deprecate __toString() method at all and detect cast events
instead. Would it make more sense? Something like this __casted().

P.S: I saw the previous conversation but hence now we have types, it would
make sense.

Midori



> As you know we have __toString method that runs whenever an object is
> typecasted to string or it is directly echoed.
>
> <?php
>
> $class = (new class{
>   public function __toString(){
>     echo "casted\n";
>     return "mahmut\n";
>   }
> });
>
> echo $class;
> $casted = (string)$class;
>
> /*
> prints:
> casted
> mahmut
> casted
> mahmut
> */
>
>
> As you know toArray() method implemented when an object is converted into
> and array and most of the time when a plain data object is sent to
> front-end.
>
> Having a magic method like __toString called __toArray would be useful to
> detect and act on conversion events.
>
> Roughly it would be like:
>
> <?php
>
> $class = (new class{
>   public function __toArray(){
>     echo "casted\n";
>     return
>     [
>       'key'=>'value'
>     ];
>   }
> });
>
>
> $casted = (array)$class;
> print_r($casted);
>
> /*
> prints:
> Array
> (
>     [key] => value
> )
> mahmut
> */
>
> What would you think? I think it would add value.

---

## #108354 — mtkocak@gmail.com — 2020-02-04T07:25:50+00:00

URL: https://externals.io/message/108351#108354 · In reply to: #108352

Oh there is even a rfc. https://wiki.php.net/rfc/to-array What is the
status of this?



> Or we can deprecate __toString() method at all and detect cast events
> instead. Would it make more sense? Something like this __casted().
>
> P.S: I saw the previous conversation but hence now we have types, it would
> make sense.
>
> Midori
>
> 
>
> > […]

---

## #108355 — Andreas Heigl — 2020-02-04T07:26:44+00:00

URL: https://externals.io/message/108351#108355 · In reply to: #108352

Hey all.

Instead of adding more magic I personally like the approach of
explicitness more and your suggest adding an interface "Arrayable"
(naming is hard and this might not be the best name) instead. Whether
that interface then defines a `__toArray()`-method or something entirely
different is then a different matter.

Additionally this would be in line with Nicolas RFC regarding
"Stringable" (https://wiki.php.net/rfc/stringable)

Just my 0.02€

Cheers

Andreas

Am 04.02.20 um 08:18 schrieb Midori Koçak:
> Or we can deprecate __toString() method at all and detect cast events
> instead. Would it make more sense? Something like this __casted().
> 
> P.S: I saw the previous conversation but hence now we have types, it would
> make sense.
> 
> Midori
> 
> 
> 
> > […]
> 

-- 
                                                              ,,,
                                                             (o o)
+---------------------------------------------------------ooO-(_)-Ooo-+
| Andreas Heigl                                                       |
| mailto:andreas@heigl.org                  N 50°22'59.5" E 08°23'58" |
| http://andreas.heigl.org                       http://hei.gl/wiFKy7 |
+---------------------------------------------------------------------+
| http://hei.gl/root-ca                                               |
+---------------------------------------------------------------------+

---

## #108358 — Marco Pivetta — 2020-02-04T10:30:48+00:00

URL: https://externals.io/message/108351#108358 · In reply to: #108351

Hey Midori,

This has been discussed in more depth 2 years ago:
https://externals.io/message/98539#98539

In practice, the `(array)` cast is one of the few operations that don't
cause observable side-effects in this programming language: let's please
keep it as such.

Marco Pivetta

http://twitter.com/Ocramius

http://ocramius.github.com/




> As you know we have __toString method that runs whenever an object is
> typecasted to string or it is directly echoed.
>
> <?php
>
> $class = (new class{
>   public function __toString(){
>     echo "casted\n";
>     return "mahmut\n";
>   }
> });
>
> echo $class;
> $casted = (string)$class;
>
> /*
> prints:
> casted
> mahmut
> casted
> mahmut
> */
>
>
> As you know toArray() method implemented when an object is converted into
> and array and most of the time when a plain data object is sent to
> front-end.
>
> Having a magic method like __toString called __toArray would be useful to
> detect and act on conversion events.
>
> Roughly it would be like:
>
> <?php
>
> $class = (new class{
>   public function __toArray(){
>     echo "casted\n";
>     return
>     [
>       'key'=>'value'
>     ];
>   }
> });
>
>
> $casted = (array)$class;
> print_r($casted);
>
> /*
> prints:
> Array
> (
>     [key] => value
> )
> mahmut
> */
>
> What would you think? I think it would add value.

---

## #108360 — mtkocak@gmail.com — 2020-02-04T10:35:29+00:00

URL: https://externals.io/message/108351#108360 · In reply to: #108358

Marco, I've read it and your argument is strong. I think my opinion
slightly moves towards Andreas, away from magic.

here is something I wrote some days ago:
https://github.com/midorikocak/arraytools/blob/master/src/ArrayConvertableTrait.php

I guess you were saying something like this would be enough.

Midori



> Hey Midori,
>
> This has been discussed in more depth 2 years ago:
> https://externals.io/message/98539#98539
>
> In practice, the `(array)` cast is one of the few operations that don't
> cause observable side-effects in this programming language: let's please
> keep it as such.
>
> Marco Pivetta
>
> http://twitter.com/Ocramius
>
> http://ocramius.github.com/
>
>
> 
>
> > […]

---

## #108361 — Marco Pivetta — 2020-02-04T10:37:25+00:00

URL: https://externals.io/message/108351#108361 · In reply to: #108360

Hey Midori,
<http://ocramius.github.com/>




> Marco, I've read it and your argument is strong. I think my opinion
> slightly moves towards Andreas, away from magic.
>
> here is something I wrote some days ago:
> https://github.com/midorikocak/arraytools/blob/master/src/ArrayConvertableTrait.php
>
> I guess you were saying something like this would be enough.
>
> Midori
>
>
Correct: an explicit `$foo->toArray()` call suffices.

For other readers, more about `$foo->toArray()` vs `(array) $foo` is
described at
https://github.com/ShittySoft/symfony-live-berlin-2018-doctrine-tutorial/pull/3#issuecomment-460441229


Marco Pivetta

http://twitter.com/Ocramius

http://ocramius.github.com/

---

## #108363 — Rowan Tommins — 2020-02-04T11:19:16+00:00

URL: https://externals.io/message/108351#108363 · In reply to: #108361

> Correct: an explicit `$foo->toArray()` call suffices.
>
> For other readers, more about `$foo->toArray()` vs `(array) $foo` is
> described at
>
> https://github.com/ShittySoft/symfony-live-berlin-2018-doctrine-tutorial/pull/3#issuecomment-460441229
>


The pros and cons of overloading casts are roughly the same as those of
operator overloading in general:

on one hand:
+ It is more succinct than calling a method
+ It aids creation of richer Domain Specific Languages
on the other:
- It is less explicit than choosing a purpose-specific method name
- It is less flexible than having multiple related methods, or a method
with parameters
- It is harder to predict behaviour at a glance


> Or we can deprecate __toString() method at all and detect cast events
> instead. Would it make more sense? Something like this __casted().

If there was a good case made for how it should work, I'd be more
supportive of a general feature to overload casting, rather than making
(array) a special case.

One of many challenges would be working out when the cast should happen
implicitly. Should "iterable $foo" trigger an array cast if the object
isn't iterable? Should foreach()? Should strict_types change that behaviour
as it does for __toString(), even though it currently only applies to
scalar types?

Regards,
-- 
Rowan Tommins
[IMSoP]

---

## #108364 — Rowan Tommins — 2020-02-04T12:30:04+00:00

URL: https://externals.io/message/108351#108364

> "(string) $var" doesn't seem a lot less explicit to me than
> "$var->toString()"
>


No, but it's significantly less explicit than "$var->getDebugString()" or
"$var->formatHTML()" or "$var->getRawText()", all of which might exist on
one class, and any of which might be chosen as the implementation for
__toString()

Regards,
-- 
Rowan Tommins
[IMSoP]

---

## #108365 — Steven Wade — 2020-02-04T12:39:37+00:00

URL: https://externals.io/message/108351#108365 · In reply to: #108354

> Oh there is even a rfc. https://wiki.php.net/rfc/to-array What is the
> status of this?

Hi there, I’m the author of that RFC. I intend to post it officially for discussion soon, I’ve just been busy and haven’t had the time that would be needed to respond to the discussion emails when they came in.

---

## #108368 — Tom Gerrits — 2020-02-04T12:55:23+00:00

URL: https://externals.io/message/108351#108368 · In reply to: #108363

>   Correct: an explicit `$foo->toArray()` call suffices.
> 
>   For other readers, more about `$foo->toArray()` vs `(array) $foo` is
>   described at
> 
> https://github.com/ShittySoft/symfony-live-berlin-2018-doctrine-tutorial/pull/3#issuecomment-460441229

This is a valid point. Perhaps another problem lies at its base: why
can one cast null to a string in PHP? Would it be more appropriate to
throw a CastError or similar? Or does casting null to another type
make sense in some scenarios?

One could go as far as to only allow types that overload the
appropriate cast operator to cast to the type without error. This
implies the question of how to handle built-in types, such as casting
floats to string.

>  - It is less explicit than choosing a purpose-specific method name

I think it's also important to mention whether this discussion is
about explicit casts only, or not - and also about implicit casts, or
coercion.

"(string) $var" doesn't seem a lot less explicit to me than
"$var->toString()", but if it is coerced automatically when being
passed to e.g. a function taking a string, that is of course a
different story.

Coercions and implicit casting using the overloaded operators could
perhaps also be limited to non-strict mode, if desired, which is also
the case for scalar types currently, IIRC.

---

## #108372 — Marco Pivetta — 2020-02-04T13:13:02+00:00

URL: https://externals.io/message/108351#108372 · In reply to: #108368

Hey Tom,



> "(string) $var" doesn't seem a lot less explicit to me than
> "$var->toString()", but if it is coerced automatically when being
> passed to e.g. a function taking a string, that is of course a
> different story.
>

`(string) $var` is less explicit because `(string)` is an operation that
applies to a wide set of types, whereas any `->` applies only to `object`
types, and also has a specific name (the method name) on its right.
Restricting that operation to fewer supported types is not feasible at this
point, since `(string) null` is very much relied upon.

Coercions and implicit casting using the overloaded operators could
> perhaps also be limited to non-strict mode, if desired, which is also
> the case for scalar types currently, IIRC.
>

Is there any newly written code that doesn't use non-strict mode at all?
Programming without `declare(strict_types=1)` seems anachronistic at this
point.

Greets,

Marco Pivetta

http://twitter.com/Ocramius

http://ocramius.github.com/

---

## #108373 — Steven Wade — 2020-02-04T13:26:34+00:00

URL: https://externals.io/message/108351#108373 · In reply to: #108354

> Oh there is even a rfc. https://wiki.php.net/rfc/to-array What is the
> status of this?

This RFC has now been moved to “under discussion” with the discussion happening here: https://externals.io/message/108369 <https://externals.io/message/108369
