Search code examples
phpimmutabilitypurely-functional

PHP pass objects by value


I'd like to implement a pure function in PHP

How do I pass an object by value and not by reference?

In other words, this is the expected output:

function change($obj) {
    $obj->set_value(2);
}

$obj = new Object();
$obj->set_value(1);
change($obj);
echo $obj->get_value(); // 1

Solution

  • read here:

    http://php.net/manual/en/language.oop5.cloning.php

    you really shouldn't pass by value, as that would require a deep copy aka. deep clone, or an insane amount allocated for for parameters..

    if you really want to, the answer is: first deep copy, then pass a reference to the copy.