A brief reminder on object scope

Every so often, you may approach a problem in a novel or unconventional manner and it reminds you just how much ground you cover as a programmer. And today at Magma Digital was no exception. I was reminded how scope works and how a non-obvious behaviour can sometimes be useful.

Cut to the chase

Private and protected methods (and member variables) can still be accessed on a first class instance of an object, providing they are accessed within the scope of that object’s definition

That’s a pretty horrific explanation of today’s exploits. I’ll try and rephrase it to sound slightly less pretentious:

Access modifiers are ignored if your instance of that class has been created inside that class’ definition

That’s not much better. I’ll just give you some pseudo code from today:

You’ll find that ConvolutedExample::baz() can successfully call a private method on an instance of ConvolutedExample, and similarly SuperConvolutedExample::baz() can create an instance of itself and call a protected method on its parents class.

Why would anyone want to do that, you might ask yourself? It’s quite useful when you start playing with identity maps or singletons, but in today’s case I wanted to var_dump some protected member variables by cloning $this and running it through get_object_vars. However, since the output was somewhat unwieldy (recursion, anyone?) I wanted to tidy up the output a bit first by calling unset($copy->protected_member_variable) on a bunch of stuff.

Tagged with: , , ,
Posted in Development, PHP

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">