> If the caller sees only the signature, then the function can do
*literally anything* to their passed by reference variable. The caller is
giving full control and "ownership" of that variable, and shouldn't make
any assumptions about what it will look like when it comes back.

Understood, only this isn't the function doing something - it's the
language.

But I guess the best thing under any circumstances is to simply avoid using
references entirely - you won't have these problems then.

The main point was, I'd still very much like to see Anthony's RFC revived
:-)

So I guess this should be updated:

"when an internal function accepts a typed parameter by reference, if the
magic cast method is defined on the passed in object, an error is raised as
the cast cannot be performed because of the reference."

Perhaps to:

"when a function receives a type-hinted parameter by reference, if the
magic cast method is defined on the passed in object, the variable in the
calling scope is immediately overwritten with the result of the type-cast."

I don't happen to like it, but that's consistent with the existing
behavior, right?


On Sun, Apr 9, 2017 at 1:07 PM, Rowan Collins <rowan.coll...@gmail.com>
wrote:

> On 9 April 2017 10:30:02 BST, Rasmus Schultz <ras...@mindplay.dk> wrote:
> >Example:
> >
> >class Foo { public function __toString() { return "foo"; } }
> >function append_to(string &$str) { $str .= "_bar"; }
> >$foo = new Foo();
> >append_to($foo);
> >var_dump($foo); // string(7) "foo_bar"
> >
> >In this example, the caller's instance of Foo gets wiped out and
> >replaced
> >by a string
>
> While this looks surprising in the form you've written it, it should only
> really be a surprise to the function author, not the caller. If the caller
> sees only the signature, then the function can do *literally anything* to
> their passed by reference variable. The caller is giving full control and
> "ownership" of that variable, and shouldn't make any assumptions about what
> it will look like when it comes back.
>
> For example, you don't even need PHP7 to do this:
>
> class Foo { public function __toString() { return "foo"; } }
> function append_to(&$str) { $str = (string)$str . "_bar"; }
> $foo = new Foo();
> append_to($foo);
> var_dump($foo); // string(7) "foo_bar"
>
> I don't think it's any more unreasonable for a reference parameter to
> change type in the parameter handling of your example function (with
> strict_types off) than inside the body of my example function. Of course,
> by setting strict_types=1, the caller can change the implicit cast to an
> implicit assertion, and get an error in your example; it won't save them
> from my example, though.
>
> Regards,
>
> --
> Rowan Collins
> [IMSoP]
>

Reply via email to