News Feed
Sections




News Archive
Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Marco Pivetta:
Accessing private PHP class members without reflection
August 15, 2013 @ 12:53:55

Marco Pivetta has posted about an interesting trick you can do with closures in PHP related to accessing private properties inside classes.

A couple of weeks ago I was working on a very tricky issue on ProxyManager. The problem is simple: instantiating ReflectionClass or ReflectionProperty is slow, and by slow, I mean really slow! The reason for this research is that I'm trying to optimize a "hydrator" to work with larger data-sets by still keeping a low initialization overhead. PHP 5.4 comes with a new API for Closures, which is Closure#bind(). Closure#bind() basically allows you to get an instance of a closure with the scope of a given object or class. Neat! That's basically like adding APIs to existing objects! Let's break some OOP encapsulation to fit our needs.

He shows how to use this "bind" feature to reach into an object, in this case a "Kitchen", and extract the value of an internal, private property. He also talks some about the performance of this method versus the more typical use of Reflection. He includes two other quick examples too - accessing the same private properties by reference and an abstracted "property reader" closure that uses the bind trick on any object.

0 comments voice your opinion now!
private method reflection closure bind alternative performance

Link: http://ocramius.github.io/blog/accessing-private-php-class-members-without-reflection

blog comments powered by Disqus

Similar Posts

Stefan Koopmanschap's Blog: public static vs static public

Brandon Savage's Blog: Stop Sacrificing Readability For Efficiency!

Sameer Borate's Blog: Refactoring 3: Replace Temp with Query

dynaTrace Blog: Top 10 Performance Problems taken from Zappos, Monster, Thomson and Co

Brandon Savage: Private Methods Considered Harmful ("Do This, Not That" Excerpt)


Community Events

Don't see your event here?
Let us know!


library laravel5 extension opinion podcast voicesoftheelephpant framework release interview example unittest introduction language install php7 community api xdebug laravel series

All content copyright, 2015 PHPDeveloper.org :: info@phpdeveloper.org - Powered by the Solar PHP Framework