+ 3
An Encapsulation problem
The encapsulation problem in PHP exists for a long time by now. Imagine having an object of a class, which can be stuffed with the properties as much as you want (example: https://code.sololearn.com/w6fLe8aX10Ve/#). The problem is that it is not safe for data in your code, right? Well, I would like to introduce you to my solution to this problem: whenever you attempt to access a property, __set() method is called, which checks if property really exist in classes scope. I would like to discuss this solution with you and also, I would like to see your own solutions. Solution: https://code.sololearn.com/wFwWnGLIXNdN/# Sorry for my english and thank you in advance!
4 Answers
+ 6
Also, this kind of solution makes encapsulation too strict, bounding programer's options inside the class methods.
+ 5
@David Carroll, You've seen my solution, right? It uses the "overloading magic methods" of PHP, and I'm asking on any other solution to this situation.
+ 2
@Freezemage: You don't really need to use wrapper methods as alternatives to the magic methods: __get() and __set().
Rather, you could embed your logic in these magic methods and add all the encapsulation controls you want from there.
I found a good example of this from the PHP.net documentation:
- http://php.net/manual/en/language.oop5.overloading.php#object.set
and tested their Example 1 in the following Code Playground link:
- https://code.sololearn.com/wbRqfmdxN6J7/#php
That said, one problem with either method is the logic embedded in these magic methods must address the encapsulation for the entire class. This could get a bit convoluted if your class has a large set of public properties.
Also, this is a tough limitation of PHP classes in that encapsulation isn't managed at the property level. Rather, all public properties are evaluated via these magic methods.
Anyway, I hope my alternative is helpful in your quest to make this better.
+ 2
@Freezemage: I did review your solution and was responding to your request for feedback on that solution. My feedback was that you don't need to wrap your magic methods with class methods.
The solution I posted was another option making better use of the magic methods via direct property accessors rather than using wrapper class methods.
Based on your response, I get the sense that I may have misunderstood your question. If this is the case, let me know how my response was not aligned with what you are looking for and we can figure out how to work through this. đ