Does PHP pass objects by reference?
I needed to know if PHP passes objects by reference, because I wanted to create some reciprocal code that would be REALLY messy if it did not.
The steps:
- Instantiate both objects
- Add the second ($two) object to the first ($one)
- Modify the second object outside of $one after adding it
- Add data to $two from inside $one
- Render the objects and see if the data that was added to $two outside of $onw was added to the $two stored in $one (confused?)
- Also, check that the data added to $two from inside of $one was set on $two
If objects are being passed by reference, then any change you make on $two whether inside the $one object or on the original $two object will be refleced when you output the individual objects separately. (i.e. they will output exactly the same)
If the objects are copied and therefore not passed by reference, then you will see that the output of the individual objects is completely different.
Here is the code:
-
class one
-
{
-
protected $dataObj;
-
public function addData($data)
-
{
-
$this->dataObj = $data;
-
}
-
-
public function __toString()
-
{
-
$this->dataObj->addData('c', 'what!?');
-
ob_start();
-
echo $this->dataObj;
-
return ob_get_clean();
-
}
-
}
-
-
class two
-
{
-
protected $data = array('a' => 5);
-
public function addData($index, $val)
-
{
-
$this->data[$index] = $val;
-
}
-
-
public function __toString()
-
{
-
ob_start();
-
var_dump($this->data);
-
return ob_get_clean();
-
}
-
}
-
-
$one = new one();
-
$two = new two();
-
-
$one->addData($two);
-
-
$two->addData('b', 'howdy');
-
-
echo $one;
-
echo $two;
So…what was the result?
-
array
-
'a' => int 5
-
'b' => string 'howdy' (length=5)
-
'c' => string 'what!?' (length=6)
-
-
array
-
'a' => int 5
-
'b' => string 'howdy' (length=5)
-
'c' => string 'what!?' (length=6)
They were exactly the same, which means that PHP passed the $two object by reference to $one. This is a cool feature because it means you can do some really cool things with objects and allows you to be defensive with your programming if someone does something out of order. There are some potential issues if your developers think that they are NOT passed by reference and that they are modifying a different $two than the one in the object. Good comments should fix that.
Sphere: Related Content