Skip to content

Instantly share code, notes, and snippets.

@smilesrg
Last active March 10, 2017 15:59
Show Gist options
  • Save smilesrg/3f2e861053da0fec41be6276d88154ca to your computer and use it in GitHub Desktop.
Save smilesrg/3f2e861053da0fec41be6276d88154ca to your computer and use it in GitHub Desktop.
Objects have to be passed by reference explicitly if function is replacing original object with cloned one.
<?php
class A {
public $property = "Default Value";
}
function clone_and_modify(A $obj) {
$cloned = clone $obj;
$cloned->property = "Modified Value";
return $cloned;
}
function pass_by_explicit_reference(A &$obj) {
$obj = clone_and_modify($obj);
}
function pass_by_implicit_reference(A $obj) {
$obj = clone_and_modify($obj);
}
$obj1 = new A();
pass_by_explicit_reference($obj1);
var_dump($obj1->property);
$obj2 = new A();
pass_by_implicit_reference($obj2);
var_dump($obj2->property);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment