Jump to content

OOP: variables passed by reference by default?


neylitalo

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?
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
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.

Archived

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

×
×
  • Create New...

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.