Posted: Wed Aug 15, 2007 11:55 am
I think I'm getting the hang of it. Confusing stuff.
A community of PHP developers offering assistance, advice, discussion, and friendship.
http://forums.devnetwork.net/
Take it from me, PHP's references are a lot less confusing at first than references in C++. Took me forever to figure out what the hell I needed with pointers pointing to references of other variables.scottayy wrote:I think I'm getting the hang of it. Confusing stuff.
Code: Select all
$o = new stdClass();
function addXToObj($obj)
{
$o->x = 42;
}
addXToObj($o);
var_dump($o); //Empty objectCode: Select all
$o =& new stdClass();
function addXToObj(&$obj)
{
$o->x = 42;
}
addXToObj($o);
var_dump($o); // object {
"x" => 42
}Code: Select all
$o = new stdClass();
function addXToObj($obj)
{
$o->x = 42;
}
addXToObj($o);
var_dump($o);Code: Select all
$o =& new stdClass();
function addXToObj(&$obj)
{
$o = 42;
}
addXToObj($o);
var_dump($o); // integer { 42 }Did you purposely assign 42 to object $o inside the function, or did you mean to go $o->x = 42; ?d11wtq wrote:Code: Select all
$o =& new stdClass(); function addXToObj(&$obj) { $o = 42; } addXToObj($o); var_dump($o); // integer { 42 }
Purposely, although I was meant to write "$obj = 42" not $o. That's why $o comes back out as an integer instead of an object. References are more literal than object handles.scottayy wrote:Did you purposely assign 42 to object $o inside the function, or did you mean to go $o->x = 42; ?d11wtq wrote:Code: Select all
$o =& new stdClass(); function addXToObj(&$obj) { $o = 42; } addXToObj($o); var_dump($o); // integer { 42 }
And inside the function, you're using $o instead of the &$obj... how come?
What makes you think so? php references are similar to C++ references (not to confuse with pointers, which are, indeed, something different).VladSun wrote: Thank you for asking this question - it made me read this manual and I found that my understanding of "PHP reference" was very mistaken (i.e. reference in PHP is not like reference in C++).
For example the behaviour of new() in PHP 4.0 ...stereofrog wrote:What makes you think so? php references are similar to C++ references (not to confuse with pointers, which are, indeed, something different).VladSun wrote: Thank you for asking this question - it made me read this manual and I found that my understanding of "PHP reference" was very mistaken (i.e. reference in PHP is not like reference in C++).