Thomas Upton
Thomas Upton

Reputation: 1899

PHP Scope and Class Instance Interaction

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?

Upvotes: 3

Views: 568

Answers (3)

Ionuț G. Stan
Ionuț G. Stan

Reputation: 179109

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.

Upvotes: 1

Josh Leitzel
Josh Leitzel

Reputation: 15199

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

Upvotes: 3

Cullen Walsh
Cullen Walsh

Reputation: 4388

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.

Upvotes: 3

Related Questions