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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With