PHP instance and class interaction

It seems that different instances of the class may know about the private variables of each other's member.

I have provided some code that tries to demonstrate my problem and I will try to explain it.

We have a class with a private member variables $hidden. modifyPrivateMembersets the value $hiddento 3. accessPrivateMembertakes Objectas a parameter and accesses its private $hidden element to return its value.

Code example:

<?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);

The output of the above code:

$ php example.php
3

Can someone explain why private members of objects are accessible to other instances of the same class? Is there any excuse for this apparent violation of the realm?

+3
3

private , , .

+3

, , factory:

class Object
{
    private $state;

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

, , , , . , , , , , . , ( ), . , - . , , .

, , , , Ruby.

+1
source

Source: https://habr.com/ru/post/1715473/


All Articles