Summary
Code example:
Class People { // private property. private $name; // other methods not shown for simplicity. }
Straight ahead. Let me assume that $name is a member of the PRIVATE class (or a property, variable, field, name it as you wish). Is there a way to do this in PHP:
$someone = new People(); $someone->name = $value; $somevar = $someone->name;
WITHOUT using __get($name) and __set($name, $value) .
Background
I needed to check the assigned $value , so I just need a getter setter like this:
getName(); setName($value);
And it is NOT necessary to overload the magic getter setter method as follows:
__get($value); __set($value, $name);
However, I just need a getter. But this is NOT what I want. It just doesn't feel object oriented, because people from a static typed language like C ++ or C # can feel just like me.
Is there a way to get and set a private property in PHP, like in C #, without using overload with the getter setter magic method?
Update
Why not a magic method?
There are rumors on the Internet that the magic method is 10 times slower than the explicit set getter method, I have not tested it yet, but this is a good thing to keep in mind. (I realized that this is not so slow, only 2 times slower, see the test result below)
I need to stuff everything into one huge method, if I use the magic method, and then separate it into different functions for each property, as in an explicit getter setter. (This requirement could be answered by ircmaxell )
Performance Overhead Benchmarking
I am wondering how the performance overhead is between using the magic method and the explicit getter installer, so I created my own test for both methods, and I hope it can be useful to everyone who has read this.
With the magic method and method_exist:
(click here to see the code)
- Getter costs 0.0004730224609375 seconds.
- Setter cost 0.00014305114746094 seconds.
With an explicit getter installer:
(click here to see the code)
- Getter costs 0.00020718574523926 seconds.
- Setter cost 7.9870223999023E-5 seconds (this is 0.00007xxx).
However, both the setter and the getter with the magic method and method exist just 2x in cost than the explicit getter setter. I think it is still acceptable to use it for a small to medium system.