Alex
Alex

Reputation: 67248

non-initialized referenced variable doesn't throw notice

I have a function that takes a variable as a reference:

function get_articles($limit = 10, &$more = false){
  $results = get_results_from_db($limit); 
  $more = ($results->found > $limit) ? $results->found : false;
  return $results->data;
}

which I use it like:

$articles = get_articles(10, $more_results);

foreach($articles as $article){
  // do stuff
}

if($more_results) // we have more than 10 results

But I don't get a notice telling me that $more_results above is undefined... Is this normal?

Upvotes: 1

Views: 148

Answers (3)

user680786
user680786

Reputation:

Yes, because $more_results will always be defined at least with false value (after calling function).
Inside function variable will not be defined, but since you doesn't read content of variable, notice is not generated.

Upvotes: 1

frostymarvelous
frostymarvelous

Reputation: 2805

I read somewhere that this is the normal behaviour. Php will always create a var if the referenced var does not exist. Trying to find it now, but you can read the below article for why not to use references in php.

http://schlueters.de/blog/archives/125-Do-not-use-PHP-references.html

Upvotes: 1

mario
mario

Reputation: 145512

It's normal.

Undefined variable notices are only generated for read accesses. When you pass a parameter by reference it's however tantamount to an implicit write access.

 $articles = get_articles(10, $more_results);
 // $more_results = NULL;  because of & here

The variable (unless existing) will be initialized to NULL prior to the function invocation in order to be able to generate a reference to that zval.

The = false default value of the function signature will only be assigned to its internal parameter if you don't pass a variable as second parameter. (Your example assigns it as value later still..)

Upvotes: 3

Related Questions