OOP - Why is this allowed?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
phpcat
Forum Newbie
Posts: 8
Joined: Thu May 28, 2009 11:23 pm

OOP - Why is this allowed?

Post 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.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: OOP - Why is this allowed?

Post 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.
phpcat
Forum Newbie
Posts: 8
Joined: Thu May 28, 2009 11:23 pm

Re: OOP - Why is this allowed?

Post by phpcat »

Thanks it makes sense now. :)
Post Reply