Jump to content

Archived

This topic is now archived and is closed to further replies.

neylitalo

OOP: variables passed by reference by default?

Recommended Posts

I was wondering if someone could help me out with this - this code and the results lead me to believe that variables are being passed by reference, but my instincts tell me that they shouldn't be.

[code]$organization = $organizationBuilder->getOrganization();
$organization2 = $organizationBuilder->getOrganization();[/code]

Here, I would assume that I'd have two independent objects, right? Read on...

[code]$organization->setName("Test Organization");

die($organization2->getName());[/code]

And now, I assign $organization a name, and get the name of $organization2. However, it spits out "Test Organization".

And if I do this:
[code]echo $organization."<br />";
echo $organization2."<br />";[/code]

I get
[quote]Object id #497
Object id #497[/quote]

So $organization2 and $organization are the same object? I think I'm missing something... can somebody explain?

Share this post


Link to post
Share on other sites
In PHP4, they aren't passed by reference unless you append the ampersand (&) to that particular class (i.e. $var = &new Class()).  

In PHP5, the default is to pass by reference.  Also, it depends on the returned value of the method, and whether or not you have cloned that object

Share this post


Link to post
Share on other sites
Damn. I was afraid of that. Thanks.

Is there any way to force it to pass by value?

Share this post


Link to post
Share on other sites
Hey neylitalo,

As far as I know, you can't stop passing by reference in PHP5.  However, if you are trying to make copies of an object, simply use the "clone" keyword.

Example:

[code=php:0]
<?php
$obj1 = new Class();
$obj2 = clone $obj1;
?>
[/code]

This should help your issue.

Share this post


Link to post
Share on other sites
I really think your problem lies inside this function:
$organizationBuilder->getOrganization();

if inside that function, you creates a new instance and return, then you should not have problem.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.