OOP - Why is this allowed?
Posted: Fri May 29, 2009 1:40 am
Code: Select all
class myClass {
private $a;
public function __construct() {
$this->a = 10;
}
public function printValue() {
print "The Value is: {$this->a}\n";
}
public function changeValue($val, $obj = null) {
if(is_null($obj)) {
$this->a = $val;
} else {
$obj->a = $val;
}
}
public function getValue() {
return $this->a;
}
}
$obj_one = new myClass();
$obj_two = new myClass();
$obj_one->changeValue(20, $obj_two);
$obj_two->changeValue($obj_two->getValue(), $obj_one);
$obj_two->printValue();
$obj_one->printValue();
$obj_one will print "The Value is: 20".
Why is this allowed? $a is a private data member. If I try to change $a from outside of an instance, I get a "Cannot access private property" error. This makes sense.
But if I pass the entire object into changeValue() of another instance and try to change the value of $a, it allows me to change it. This doesn't make sense to me.