views:

171

answers:

3

It seems as though different instances of a class can know about each others' private member variables.

I have provided some code that attempts to showcase my issue, and I will try to explain it.

We have a class with a private member variable, $hidden. modifyPrivateMember sets the value of $hidden to 3. accessPrivateMember takes an Object as a parameter and accesses its private $hidden member to return its value.

Example code:

<?php
// example.php

class Object {
    private $hidden;

    public function modifyPrivateMember() {
        $this->hidden = 3;
    }

    public function accessPrivateMember(Object $otherObject) {
        return $otherObject->hidden;
    }
}

$firstObject = new Object;
$firstObject->modifyPrivateMember();


$otherObject = new Object;
echo $otherObject->accessPrivateMember($firstObject);

Output of the above code:

$ php example.php
3

Can anyone explain why private members of objects are accessible to other instances of the same class? Is there some justification for this ostensible breach of scope?

+3  A: 

That's just how php works. It's the same as how Java works. See http://php.net/manual/en/language.oop5.visibility.php for more info.

phantombrain
The fact that Java works like this may actually be a valid answer why PHP works the same. But it's interesting to know the real answer that applies to all such languages.
Ionuț G. Stan
+1  A: 

private means it's restricted to only that class, not only that object.

Josh Leitzel
+1  A: 

The only situation in which this behavior seemed useful was in a factory function:

class Object
{
    private $state;

    public static function makeObject()
    {
        $obj = new Object;
        $obj->state = 'some state';
        return $obj;
    }
}

Even in this case, there are better solution and I agree with you that it is a breach of scope, although not that big in my opinion. After all, the one who writes the class decides if she needs to access private members from objects passed as arguments. So, it may seem useless (even to me), but you never know. It's not like you're exposing your internals to subclasses or something. It all happens in the same class and it's your business what you're doing in there.

By the way, one language that implements access modifiers per object and not per class is Ruby.

Ionuț G. Stan