subtilités de PHP

aaahhh… les pointeurs… ça me manquait presque…

Je viens de découvrir une jolie subtilité de PHP qui nous a bien fait flipper parce que nos transaction ne fonctionnaient plus :

Global vars and references

Storing references to global variables inside a function is a problem, as a global var inside a function seems to be nothing but a local var containing a reference to the global. Confused? An example:

function something()
{
  global $someObjectRef;
  …
  $someObjectRef =& new someClass();
}

If you do this and look at $someObjectRef from outside the function (after calling the “something()” function), you will find it as it was before calling the function (probably empty).

The thing is, by using the “global” keyword you create a local variable pointing to (containing a reference to) a global variable. But as soon as you store another references into this local variable (by doing the "$someObjectRef =&… "), it’s not pointing the the global anymore! You simply “redirect” your local var, not even touching the contents of the global. So, what to do?

To assign object refs to global vars inside a function, don’t use the “global” keyword! Instead use the $GLOBALS dict, like this:

function something()
{
  … 
  $GLOBALS['someObjectRef'] =& new someClass();
}

That way, after calling something() the global variable someObjectRef will contain a reference to the newly created object.

source : http://www.obdev.at/developers/articles/00002.html