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

Devis Lucato's Blog:
Anonymous objects in PHP - Composition, Mocks, Refactoring
Nov 23, 2010 @ 19:17:53

In a new post to his blog Devis Lucato points out something he noticed when working with objects and anonymous functions/closures - they're not all as they seem.

Both solutions allow to instantiate an anonymous object with properties. They are used as value objects and have no other purpose than storing values, so no logic can be included and they don't come with methods. They can be used as function parameters instead of arrays, for instance. PHP 5.3.0 introduced anonymous functions and closures, so it is now possible to attach functions to these VOs (*). [...] The first thing to notice is that these properties are not methods but callable functions:

In his example, an anonymous function dynamically appended to an object doesn't have access to a property set on the object just one line before. There's a way around it with call_user_func, but it's not practical. His proposed solution is to create a type of Anonymous class that uses the __call method to catch the methods and translate them into calls to call_user_func_array automatically.

tagged: anonymous objects composition mocking refactoring

Link:


Trending Topics: