Haravikk Haravikk - 1 year ago 102
PHP Question

Variadic Variables by Reference

I was hoping to create a method through which I could "bind" several variables by reference such that they can be reused to pass new data to an object, essentially doing the same thing that PHP's

method does.

However, it does not appear to be possible to specify that variadic arguments should be by reference, as-such they are always passed by value.

To illustrate, consider this example:

class MyType {
private $bound = [];
public function bind(...$vars) {
$this->bound = [];
foreach ($vars as &$v) { $this->bound[] = &$v; }
public function echo() {
foreach ($this->bound as $v) { echo "$v\n"; }

$a = 'Wrong'; $b = 'Wrong'; $t = new MyType();
$t->bind($a, $b);
$a = 'Right'; $b = 'Right';

What I want is for the output to be two lines saying "Right", rather than "Wrong". Currently I'm achieving this using the following nasty workaround for the bind method:

public function bind(&$var0, &$var1 = null, &$var2 = null, &$var3 = null, ...$overflow) {
if (!empty($overflow)) { throw new Exception('Too many arguments'); }

$this->bound = [&$var0];

if ($var1 === null) { return; }
$this->bound[] = &$var1;

if ($var2 === null) { return; }
$this->bound[] = &$var2;

if ($var3 === null) { return; }
$this->bound[] = &$var3;

But obviously this limits me to only the number of variables I am willing to define. This also has the side-effect that I can't pass values of
into the method (as it is misinterpreted as a non-existent argument).

What I'm wondering is whether there is another way I can achieve this that isn't so boilerplate heavy?

Answer Source

The syntax for variadic parameters by reference is:

public function bind(&...$vars) {


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download