Quick variable duplication?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ben.artiss
Forum Contributor
Posts: 116
Joined: Fri Jan 23, 2009 3:04 pm

Quick variable duplication?

Post by ben.artiss »

Hi everyone,

I've seen this crop up a few times now and would just like to clarify what's going on with it:

Code: Select all

$varname = $GLOBALS['varname'] = new classname;
Does this mean that $GLOBALS['varname'] is the same as $varname, and there is only one instance of classname (assuming $varname is in the global scope)?

So taking a slightly different approach:

Code: Select all

$var1 = $var2 = 'anything';
Does this mean that $var1 and $var2 are the same value, but declares both variables for separate usage? I.e. are you effectively duplicating the variable with the added '$var2 = ' ? (Come to think of it, that doesn't give a parse error does it!?). So going one step further, could you declare as many vars as you want like this, e.g. $var1 = $var2 = $var3 (etc) = 'value' ?

Thanks, Ben
Defiline
Forum Commoner
Posts: 59
Joined: Tue May 05, 2009 5:34 pm

Re: Quick variable duplication?

Post by Defiline »

Code: Select all

$varname = $GLOBALS['varname'] = new classname;
This is gibberish!
$GLOBALS - is a global array that contains ALL variabler including $_SERVER, $_ENV and etc.
If you do so:

Code: Select all

$varname = new classname();
You can get access to this variable:

Code: Select all

$GLOBALS['varname']->obj();
But:

Code: Select all

$somevar = new ClassName();
$newvar = $somevar; // $newvar contains the LINK to $somevar (in PHP 5)
This is correct

Code: Select all

$var1 = $var2 = 'anything';
ben.artiss
Forum Contributor
Posts: 116
Joined: Fri Jan 23, 2009 3:04 pm

Re: Quick variable duplication?

Post by ben.artiss »

Great stuff thanks for clearin that up Defiline - I didn't see the point of the $var = $GLOBALS['var'] = new class either!

Thanks, Ben
Post Reply