Alejandro Rodriguez
Alejandro Rodriguez

Reputation: 252

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

Upvotes: 1

Views: 5157

Answers (1)

Henrik
Henrik

Reputation: 2229

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.

Upvotes: 4

Related Questions