aw crud
aw crud

Reputation: 8891

Should PHP variables be initialized prior to use as an OUT function parameter?

What is the correct way to write code that calls a function that accepts a variable pointer and changes the value?

The following works, but my IDE complains that $v is an undefined variable, which it is until the function it calls sets a value:

function foo(&$bar) {
  $bar = 12345;
}

foo($v);

Should I initialize $v first to satisfy my IDE? Or is there a better way to do this?

$v = NULL;
foo($v);

Upvotes: 4

Views: 527

Answers (1)

zzzzBov
zzzzBov

Reputation: 179216

When passing a variable by reference to a function, you need to have a reference to the variable from the calling code. To have a reference, the variable needs to exist. To exist, the variable needs to be initialized.

I recommend setting it to a reasonable default value. If the reasonable default is null, then use null. In some cases it may be more reasonable to use '' or 0 depending on what type of value you want the variable to hold.

Upvotes: 6

Related Questions