Ga direct naar


PHP myths confused

Thursday 18 December 2008 17:16 Every now and then, when you least expect it, PHP behaves in an unexpected way. I was ready to file a bugreport, when I noticed it was documented behaviour.
By Casper Langemeijer

Take a look at the following code:

function b() 
{
global $a;
$b = 'bar';
$a = &$b;
}

$a = 'foo';
b();
echo $a;

What do you think is the value of $a after calling b()? The correct answer is 'foo'. If we remove the ampersand in '$a = &$b;' the value will be: 'bar'.

This behaviour can be explained as following:

In function b() the 'global $a' statement creates new a local variable $a as a reference to the global $a variable. '$a = &$b' then changes the local $a variable as a reference to $b. The global $a variable is not touched.

To achieve a sane result use the following construction, create the reference first, then assign a new value:

function b() 
{
global $a;
$b = &$a
$b = 'bar';
}

I still think this should be considered flawed implementation, if not simply broken.

«Back

Reactions on "PHP myths confused"

1 2Last page
Jack n Jill
Placed on: 05-20-2013 19:51Quote
This is excellent post for PHP geeks out there.
<a href="http://www.authenticubatours.com/">cuba tours</a>
1 2Last page
New post
You can use UBB Tags in your message

Procurios zoekt PHP webdevelopers. Werk aan het Procurios Webplatform en klantprojecten! Zie http://www.slimmerwerkenbijprocurios.nl/.


Hello!

We are employees at Procurios, a full-service webdevelopment company located in the Netherlands. We are experts at building portals, websites, intranets and extranets, based on an in-house developed framework. You can find out more about Procurios and our products, might you be interested.

This weblog is built and maintained by us. We love to share our ideas, thoughts and interests with you through our weblog. If you want to contact us, please feel free to use the contact form!

Contact us!


Showcase

  • Klantcase: Bestseller
  • Klantcase: de ChristenUnie
  • Klantcase: Evangelische Omroep
  • Klantcase: de Keurslager
  • Klantcase: New York Pizza
  • Klantcase: Verhage

Snelkoppelingen