10

I just love PHP. You can do so much awesome stuff with it. Here, let me show you:

How to READ a private member of an object:
$reader = \Closure::bind(function ($instance, $name) {
return $instance->{$name};
}, null, $instance);
$value = $reader($instance, $name);

How to WRITE a private member of an object:
$writer = \Closure::bind(function ($instance, $name, $value) {
$instance->{$name} = $value;
}, null, $instance);
$writer($instance, $name, $value);

See? Just like that. This is really amazing stuff. I don't know of any other languages that allow this.

Comments
  • 5
    You've got reflection in Java.
  • 4
    You have pointer-magic in c/++
  • 4
    Python's introspection will let you do the same. I mean, it doesn't have encapsulation the same way the others mentioned do, but you can definitely cook up very similar functions.
  • 13
    Yeah. Because breaking encapsulation and meddling with other objects internal state is _such_ a great idea to begin with.
  • 2
    @Makenshi I guess this is meant as a rescue strike to hack into an existing library you may not be able to edit.
    It is truly not a good idea, but it is possible.
  • 3
    Haha you can do this is most languages
  • 5
    Anything lauding praise upon PHP must be sarcasm.
  • 2
    @Ashkin amen to that 😂
  • 1
    Being able to break data encapsulation is a good thing? Please tell me you're being sarcastic.
  • 2
    Just to clearify: Yes, this entire rant is highly sarcastic. Of course it is a problem to break data encapulation just like that. However, I have to admit that this trick was very helpful when I recently played around with third party packages that used some sort of licensing system. So this does have a reason to exist. I just struggle to find a good one. (I don't consider it a good thing if the only useful application for it that I managed to come up with is a license crack.)

    And for those of you who compared this to reflection in other languages: I am aware of that. PHP also comes with reflection. This is just another way to access private members. So if reflection is the general exception for data encapsulation, PHP still breaks it.
  • 1
    Ruby:

    object_with_private_method.try(:private_method)

    Boom!
Add Comment