I was writing some function and I needed to return object. Actually that function just take object as parameter, drag out attributes, do some work and set new attribute to object and return it. When I am doing this I always consider if I should return the same object or create new one. The point is that when I return the same object, it may lead to confusing mistakes. Consider the piece of pseudo-code below:
We have records in database and we store them as name part which look like "prefix-name" and data part. User puts the name and our dummy management add the prefix part. If we are dummy too and do this as object reference we are lost.
class DummyObject {
public $name;
public $data;
}
class DatabaseManager {
public function load(DummyObject $object){
//Retrieve data from database and set them.
$this->makeRightPath($object);
$object->data = "Data with long story to tell";
return $object;
}
//This sets the correct name of record in DB
private function makeRightPath(DummyObject $object) {
$object->name = "prefix-" . $object->name;
return $object;
}
}
$object = new DummyObject();
$object->name = "DummyName";
$mng = new DatabaseManager();
$loaded = $mng->load($object);
echo $loaded->name;
The result of echo will be "prefix-DummyName" which user obviously does not want to see. In addition if we want to load (or save etc.) the same object again it leads to loading with name "prefix-prefix-DummyName" which is actually not in DB.
I know this is not the best example of what I wanted to say (it is my first example ever) but it shows you how important is thinking about references in function calling.