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]

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to