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
Taco
Placed on: 12-18-2008 18:37Quote
Taco van den Broek
User icon
I'd like to correct your article: the corect answer to "What do you think is the value of $a after calling b()?" is "baz" in my case Wink

Nice post!
garfix
Placed on: 12-18-2008 20:30Quote
Patrick van Bergen
User icon
to be continuum
Thanks Casper, your explanation is very clear Smile
Edited
garfix has edited this message on: 12-18-2008 20:30
Loïc Hoguin
Placed on: 12-19-2008 00:14Quote
I wouldn't recommend using global variables in a function, and would recommend even less using references to global variables. But if I had no choice I'd rather use the $GLOBALS array. It may be a bit longer to write but it is easier to read and it doesn't suffer from this problem.

The implementation works as expected according to your (very clear) explanation, but it sure is misleading when you don't know exactly how the global keyword works.
Casper Langemeijer
Placed on: 12-19-2008 09:11Quote
User icon
Thanks for your comment Loïc. And I agree that using the $GLOBALS superglobal is more clear, but only because the behaviour I describe in my article is not what you'd expect.

I don't like using $GLOBALS though. Using the global keyword is similar to the way other languages solve the same problem. The concept of superglobals only exists in the PHP language.
David Otton
Placed on: 12-24-2008 04:56Quote
I hit the same thing about a month back, and came to the same conclusion as you ("it's broken!"). A guy called pestaa popped up in the comments and gave me a pretty clear explanation. It boils down to "it's a reference, not a pointer".

Link: http://www.otton.org/200...ces-globals-workaround/
prada high top sneaker
Placed on: 09-22-2012 05:30Quote
There is no doubt that to incite the imagination of the designers and trigger their inspiration is relative to whether the culture of enterprises supports imagination and revolution or not.so we think highly of innovative style and delicate in craftsmanship,prada high top sneaker mix of the unique design concept,you can have a try. http://www.cheapprada-shoes.org
prada high top men sneakers and prada patent leathers shoes are new for this year and beyond,they are not only a concrete expression of the concept of fashion,but also is a natural manifestation of noble temperament,match with suit and present formal occasion is perfect.besides there are many new arrivals for your choice. http://www.cheapprada-shoes.org
First lady of Italian fashion and all-around smart prada women Casual Shoes recently voiced her opinion on the matter of Italian brands leaving Italy in a rare interview with La Republicca, and it’s not particularly optimistic. This brand cross our borders, the credit, glamour, fame and decision making is in the hands of others, and we are abandoned, downgraded. Most of people are fond of prada high top sneakeras the exquisite workmanship. http://www.cheapprada-shoes.org
We are basic on the principle"Credit Standing First and Customers First"to win new and old customer'praise,discount prada shoes you can trust,it made of fist class material,it mix of unique design concept and the production process,each pair of shoes is unique,you must can buy your satisfied item.
xsdfsafa
Placed on: 09-27-2012 03:32Quote
The counterfeiters applause to north face jacket sale maneuver for that finest diplomacy Northern Encounter region wallets to obtain classic Denali in addition elevated prosperity designs; this is really thickness you really obtain that they're whole inform.Aside from realizing trigger to obtain a loving along with the weather, Northern Encounter region wallets is going to be aswell acutely fragile in addition long-lasting.
XSAFSAFASFA
Placed on: 09-27-2012 03:35Quote
The counterfeiters applause to <a href="http://www.baynfjackets.com/">north face jacket sale</a> maneuver for that finest diplomacy Northern Encounter region wallets to obtain classic Denali in addition elevated prosperity designs; this is really thickness you really obtain that they're whole inform.Aside from realizing trigger to obtain a loving along with the weather, Northern Encounter region wallets is going to be aswell acutely fragile in addition long-lasting.
northface
Placed on: 10-09-2012 10:38Quote
We have various cheap north face jackets with the discount prices at our store. Find affordable stylish designer and save on north face jackets. Quickly to buy it!
chen xiao dong
Placed on: 10-10-2012 09:49Quote
Up to 70% off on cheap north face jackets,discount north face jackets and accessories with 30-day money back guarantee and fast free shipping!


If you want to buy the best quality of Fake Oakley Sunglasses with lowest price. our Fake Oakleys are your best choice! Don't hesitate, choose replica oakley sunglasses you like now.


Women and man burberry scarff sale,all choice burberry scarves,free shipping for your attire. Times are changing so let the Classic burberry scarf sale match for you


cheap oakley sunglasses and Discount Oakley Sunglasses on sale. Welcome to our Oakley Sunglasses Outlet store selection of cheap oakley sunglasses eyewear.
North Face Outlet Locations
Placed on: 10-26-2012 14:13Quote
Endless jackets source ( the great source of light ) the north face ( jackets ) glory to the name of the goddess, store borrow power ... ... Break -- energy ( material ) law "
Along with Ling and small pure spell over, in front of <a href="http://www.hinorthfaceoutletstore.com/"><strong>North Face Outlet Locations</strong></a> the monster action suddenly freeze-frame, then see locations space around suddenly break into many pieces like a mirror, and in situ and left a huge black hole, and the floor pieces haven't come yet and landing by black hole sucking hole with subsequent thoroughly. Time began to become smaller, finally turned into a little black dot.
shaku
Placed on: 11-09-2012 03:35Quote
the north face coats Is Warmer Than Other CoatsHowever, to the clothes in this complex market, pick out a www.realnorthfacejacket.com and good winter also it is not easy. But never mind, here are some standard allows you to reference, so North Face Winter Coats Mens Denali can determine which one to buy. The winter season comes again, Extremes in temperatures during this period ensure us that another bout of the flu is coming.
shaku
Placed on: 11-09-2012 03:40Quote
Though colds will not kill you, your immune north face winter jackets system can certainly be damaged during this time, thus giving opportunistic microbes the chance to wreak havoc on your North Face Winter Coats For Womens is important to keep your body warm in winter. But some people like to approach to fashion, so they throw away heavy dress, then turned into www.realnorthfacejacket.com which look like more stylish.
zllily
Placed on: 11-21-2012 04:14Quote
Appropriate for heat listed below 61 qualifications Fahrenheit, <a href="http://www.thenorthfacesuk.com/"><strong>north face parka</strong></a> the following protected heavy-duty coat includes 675 goose pack, your coyote <a href="http://www.thenorthfacesuk.com/">www.thenorthfacesuk.com</a> cover plus span this includes a thighs and legs. <a href="http://www.thenorthfacesuk.com/"><strong>north face nuptse</strong></a> is really Arctic Computer polyester plus egyptian cotton seed covering has reflective record to get great rankings plus connectors to get training with for the duration of attempt cases.
zllily
Placed on: 11-21-2012 04:29Quote
The greatest feature about the the north face clearance Triclimate Jacket is how it can change itself to suit the weather around you. The inner layer is a cosy fleece which performs as a way of keeping warm, and the outer is a waterproof shell. One can use both of these layers in isolation to be warm or dry, or use them in combination to be warm and dry. The great fact is that all three layers are interlocked using zip technology, which prevents ease of access and prevents is from getting 'bunched up' alike other jackets. Also, a great point is that the hood upon the north face on sale folds up into a neat collar - who says winter north face sale can't have style!
zllily
Placed on: 11-22-2012 04:01Quote
A Quebecwww.thenorthfacesuk.com Environments north face coats can continue to keep you actually heated while in the absolute depths of yournorth face clothing .The last model of all the way down coat is definitely Marmot 8000M Parka. A Marmot 8000M Parka is actually a water-resistant, breathable coat by using 500 pack goose all the way down feathers.
martina
Placed on: 12-04-2012 12:24Quote
This behaviour can <a href="http://www.examsmafia.com/70-482.html">70-482</a> be explained as afterward In action b() the 'global $a' account creates new a bounded capricious $a as a advertence to <a href="http://www.examsmafia.com/70-482.html">70-482 exam</a> the all-around $a variable. '$a = &$b' again changes the bounded $a capricious as a advertence to $b. The all-around $a capricious is not touched. <a href="http://www.examsmafia.com/70-482.html">http://www.examsmafia.com/70-482.html</a>
Allenwood
Placed on: 12-08-2012 13:01Quote
<a href="http://www.searchmarketinggroup.co.uk/our-services/organic-search">Search Marketing</a> - Welcome to the Search Marketing Group, a search marketing company specialising in SEO and search marketing in the UK.
readf
Placed on: 12-12-2012 16:43Quote
Free Slot The Temple of Shangri-la the floor pieces haven't come yet and landing by black hole sucking hole with subsequent thoroughly. Time began to become smaller, finally turned into a little black dot.
robert
Placed on: 12-12-2012 16:45Quote
seo changes the local $a variable as a reference to $b. The global $a variable is not touched.
rock
Placed on: 12-16-2012 10:04Quote
This is because first impressions are always important to professors. Consider each essay introduction sample below for an essay on the topic “Presidential Candidates and Poverty in America:”
<a href="http://www.123essay.net/essay-writing-service/">here</a>
detain
Placed on: 12-19-2012 07:57Quote
When you fly with Krystal,north face breast cancer you are in one relaxing journey to your destination because the flight is tailored specifically to what you need.north face pink ribbonbreast cancer north face. This again reduces the cost factor and companies get to interact with their target markets directly. Because mailing lists contain highly targeted audiences, there are increased ch The information contained in the B2B mailing list is collected and compiled from various sources like annual reports of companies, north face breast cancer jacket , yellow pages in addition to online resources.
Zerom
Placed on: 03-05-2013 12:45Quote
fred
Placed on: 04-10-2013 05:19Quote
Your post is expressing what i actually wanted to know, thanks alot! <a href="http://www.thelodgingsource.com/">Lodging Articles</a>
awesome
Placed on: 05-13-2013 14:59Quote
CONTINUOUS INK SUPPLY This is site to spent time on .I just stumbled upon your chatty blog and desired to say that I have really enjoyed reading your very well written blog posts. I will be your frequent visitor, that's for sure.
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