php5 pass by reference

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
thinsoldier
Forum Contributor
Posts: 367
Joined: Fri Jul 20, 2007 11:29 am
Contact:

php5 pass by reference

Post by thinsoldier »

Update #2
ini_set('zend.ze1_compatibility_mode',0);
Just needed to turn that off. This thing has caused me tons of problems in the past with SPL classes. I think I'll just always keep it turned off from now on.

zend.ze1_compatibility_mode boolean
Enable compatibility mode with Zend Engine 1 (PHP 4). It affects the cloning, casting (objects with no properties cast to FALSE or 0), and comparing of objects. In this mode, objects are passed by value instead of reference by default.

Updated with simplified code.
Shouldn't the last line echo 'banana'?

Code: Select all

 <?
class object
{ var $testvar = ''; }
 
 
$A = new object;
$A->testvar = 'apple';
 
echo '<p>A = '.$A->testvar.'</p>';
 
$B = $A;
echo '<p>B = '.$B->testvar.'</p>';
 
$B->testvar = ' BANANA - changed testvar value with B';
 
echo '<p>A after changing B = '.$A->testvar.'</p>';
?> 
The output I get is:

Code: Select all

A = apple
 
B = apple
 
A after changing B = apple
But if I change line 11 to $B = &$A; I get what I expected:

Code: Select all

A = apple
 
B = apple
 
A after changing B = BANANA - changed testvar value with B
So my question is: Wasn't php 5 supposed to pass objects around without me needing to use the '&' all the time? It's not doing that on my server.
Last edited by thinsoldier on Fri Jan 18, 2008 11:11 am, edited 7 times in total.
Warning: I have no idea what I'm talking about.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: php5 pass by reference

Post by pickle »

Dude - ask a question.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Re: php5 pass by reference

Post by Ambush Commander »

I think the question is in the code.

I'm under the impression that the code you've given should work as you expect it to, due to PHP passing objects "by value". Can you give us the full class definitions so I can test it out?
Post Reply