Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is an object returned from a function?

Tags:

object

php

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)
like image 961
okey_on Avatar asked Aug 14 '26 05:08

okey_on


2 Answers

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.

like image 67
deceze Avatar answered Aug 16 '26 20:08

deceze


Consider the following example:

$var = 'test';
$ref = &$var;
unset($ref);
echo $var; // Echoes "test".

The unset is only removing the reference of $var to $ref, not destroying the original variable that $ref refers to. This is similar to your example of objects being references, and the garbage collection only removes the variable's reference to the object, but the object still exists in memory.

See http://php.net/manual/en/language.references.unset.php for more details.

like image 21
Ethan Avatar answered Aug 16 '26 18:08

Ethan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!