I’m confused about the following output
class A{
public $v = 10;
function add($number){
$this->v +=$number;
}
}
$a = new A;
echo $a->v . "\n";
$a->add(5);
echo $a->v . "\n";
Why does the second line output 15 instead of 10? I thought changes made to values inside a function do not propagate outside of the function unless you pass by reference.
Your remark “changes made to values inside a function do not propagate outside of the function” goes for parameters. Which can be passed ‘by value’ or ‘by reference’ for instance:
In the sample above, $b will become 15 only if it is passed by reference to the function.
In your case, you’re not modifying the parameter at all. You’re not modifying a local variable either.
You’re modifying the property
vof the object.$thisis a special variable, that is local to the function, but references the object. The actual variable you modify is not$this, nor the parameter, but a property of$a.