Re: How do I force to pass an argument by reference?
| From: | Johannes Schlüter | Date: | Fri, 12 Feb 2016 19:37:58 +0000 |
| Subject: | Re: How do I force to pass an argument by reference? | ||
| References: | 1 | Groups: | php.pecl.dev |
| Request: | Send a blank email to pecl-dev+get-13540@lists.php.net to get a copy of this message | ||
Hi,
On Fri, 2016-02-12 at 16:34 +0600, Ruslan Osmanov wrote:
> Please help me to understand what's wrong with my code, or how do I
> force passing by reference?
From what I can tell the code seems to be correct. The flag is rightly
set. The only thing which comes to mind is that the error you're citing
is produced by the compiler, not during execution. So maybe there's some
magic in the compiler involved.
Anyways: I wonder why that is needed. You are passing an object, and an
object is passed by handle, so you can manipulate the same object if if
passed by value. Taking a reference means that the user eventually can
replace the object and references are bad.
<?php
class C {
private $o;
public function __construct(stdclass &$o) {
$this->o = &$o;
}
public function getO() {
return $this->o;
}
}
$o = new stdclass();
$c = new C($o);
$o = 42;
var_dump($c->getO());
?
int(42) // no object anymore!
Also, at least in PHP 5, you usually get a notable performance penalty
as copy-on-write will prevent copies while references disable
copy-on-write. I haven't benchmarked this in PHP 7.
johannes
Attachment: [application/pgp-signature] This is a digitally signed message part signature.asc
Attachment: [application/pgp-signature] This is a digitally signed message part signature.asc