okeyxyz okeyxyz - 23 days ago 6
PHP Question

How is an object returned from a function?

I don't understand how it's possible to return an object from a function. Since objects are passed and returned by reference, If I created an object in a function, I'd expect such object to be destroyed after the function finishes executing. So such returned object reference should be referring to non-existing(destroyed) object. But my object created within a function is successfully returned. How come??

class O{
public $ppty = "ppty value";
}

function f1(){
$o1 = new O();
return $o1;
}

var_dump(f1());


**Result:**
object(O)[15]
public 'ppty' => string 'ppty value' (length=10)

Answer Source

A variable "holding" an object is actually holding a reference to the object. The object exists somewhere in memory, the variable referring to the object just holds the memory address (oversimplified). That's the reference. When returning that reference or passing it somewhere or assigning it to another variable, a copy of that reference is made (meaning the memory address value is copied; e.g. you return the value 0xDEADBEAF from your function; again, oversimplified). Those references are counted as a property of the object; only when the reference count reaches 0 (no variable is holding a reference to the object anymore), is the object garbage collected.