Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php/OOP How to avoid instances of the same class to access private properties/methods from other objects

Tags:

oop

php

I know that private visibility in most of the OOP languages (if not all) define privacy in a class basis, i.e. different instances of the same class, can access private properties/methods of each other.

I want to prevent this and I want to know what is the best design/implementation in order to do this without a negative performance impact.

For example, I know that I could implement an AOP and use notations, but this would lead to a performance decrease since the languange engine would have to create the reflection of the class and check the annotation. So, basically, my question is, what is the best way to avoid instances of the same class to access each other's private methods/properties?

Example:

class Product
{
    private $_prize;
    public function __construct($prize)
    {
        $this->_prize = $prize;
    }

    public function calculateDiscount(Product $extraProduct)
    {
        $extraProduct->_prize = 0; //How to avoid this?
    }
}

$productA = new Product(10);
$productB = new Product(25);
$productA->calculateDiscount($productB);
like image 629
taxicala Avatar asked Jun 22 '15 13:06

taxicala


1 Answers

Simply don't write code which accesses other entities' privates, period. The visibility modifiers are there to help you not shoot yourself in the foot too easily. They're not a lock and key. There are any number of ways in which you can still "circumvent" "access protection". Just be a responsible adult and not modify properties except when you write a $this-> before it.

like image 190
deceze Avatar answered Sep 30 '22 14:09

deceze