$mt = microtime(TRUE);
foreach($y as $k => $v) {$z->$k = $v;}
$a = microtime(TRUE) - $mt;
print "Execution Time: " . ($a) . "\n";
Monday, May 25, 2020
Friday, February 14, 2020
Are PHP Objects passed as a value?
Yes they are, but as a copy of a value of a reference. Same as in Java.
Example below is showing how the Person type arguments are passed. In the point of entry of the methods changeName() and changeNameToNull(), $person reference copy is made.
From that point, a new reference can change the $person object in changeName(), as it has a reference to it. On the other hand, changeNameToNull() shows it is a copy of a reference, as setting to NULL value just destroys the copied reference, but not the $person object, thus original reference also.
<?php class Person { public $name = 'Mike'; } class Change { public function changeName(Person $person): void { $person->name = 'Jack'; } public function setPersonToNull(Person $person): void { $person = null; } } //set person to NULL $person1 = new Person(); (new Change())->setPersonToNull($person1); var_dump($person1); //change name to Jack $person2 = new Person(); (new Change())->changeName($person2); var_dump($person2);
Result:
object(Person)#1 (1) {
["name"]=>
string(4) "Mike"
}
object(Person)#2 (1) {
["name"]=>
string(4) "Jack"
}
Subscribe to:
Posts (Atom)