Page 1 of 1

OOP - Why is this allowed?

Posted: Fri May 29, 2009 1:40 am
by phpcat

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_two will print "The Value is: 20".
$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. :? Can someone explain it? Thanks.

Re: OOP - Why is this allowed?

Posted: Fri May 29, 2009 2:00 am
by requinix
"private" applies to an entire class, not to just one instance of it.

It means the class can modify its own values regardless of exactly which object the value is in. In the end it's just a myClass function trying to modify a myClass variable.

Re: OOP - Why is this allowed?

Posted: Fri May 29, 2009 2:05 am
by phpcat
Thanks it makes sense now. :)