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

Mark Baker:
Using PHP Anonymous Classes as Package Private Classes
Jun 26, 2018 @ 20:09:36

Mark Baker has a post to his site about some of the interesting things you can do with anonymous classes, focusing on their use outside of testing (as he has in previous articles).

I’ve written before about the benefits of using PHP’s Anonymous Classes for test doubles; but Anonymous Classes also have potential usecases within production code as well. In this article I’m going to describe one such usecase that can be particularly useful within libraries, and that is replicating the access of Package Private (in Java), or Protected Internal Classes (as per C#).

He briefly explains what the package private/protected internal classes functionality entails before getting into his own use of the method with the PHPExcel/PHPSpreadsheet packages. He defines how he thinks the system should be structured and the isolation the anonymous classes would provide (without having to make whole separate classes just for that). He creates a class that has all public methods accessible but cannot be instantiated from outside the library. He shares some example code to illustrate his point, walking through each step to show what it's doing and how.

tagged: anonymous class package private class tutorial phpexcel

Link: https://markbakeruk.net/2018/06/25/using-php-anonymous-classes-as-package-private-classes/

Trending Topics: