-1

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?

dWinder
  • 11,597
  • 3
  • 24
  • 39
  • 2
    Why will you get 1 as you have called the loop to iterate 10 times – M A SIDDIQUI Jan 10 '17 at 15:02
  • 1
    I think what he's trying to get at is that `$a` is being manipulated within the local scope of the function and that `$v` is accessing `$a->var` in the global scope.. and as such should have the initial value of `1` rather than `11` ... the short answer is, *it doesn't work like that* but I think I can see where he's coming from. – CD001 Jan 10 '17 at 15:16
  • Possible duplicate of [Are PHP Variables passed by value or by reference?](http://stackoverflow.com/questions/879/are-php-variables-passed-by-value-or-by-reference) – Winter Jan 10 '17 at 18:00

2 Answers2

1

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.

in need of help
  • 1,606
  • 14
  • 27
0

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.