I have the simple code:
class A {
public $var = 1;
function inc() {$this->var++;}
}
function foo($a) {
for($i = 0; $i < 10; $i++) {
$a->inc();
}
}
$a = new A();
foo($a);
$v = $a->var;
echo "var value is $v \n";
I was expecting to get printed the value of 1 but I get 11. shouldn't PHP pass argument to functions with copy-constructor?
PHP does have a copy constructor but it copies shallowly so the object passed to foo is a new copy but it has a reference to $var that points to the same value as $a->var. If you would have done foo(clone($a)) then you would have gotten the answer you're expecting.
You already have $var=1
and you are incrementing every 10 times. That means that your for loop runs 10 times and it gets incremented as you have $this->var++
in class A inc method
. So To get your result your $var
should be equal to -9 or else you should set the for loop to run single time and set the value of $var
as 0 by default.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.