Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 227
Thomas Upton Avatar asked May 17 '26 11:05

Thomas Upton


1 Answers

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

like image 154
Josh Leitzel Avatar answered May 20 '26 01:05

Josh Leitzel