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?
Link to comment
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
Link to comment
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.
Link to comment
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.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.