Refactoring PHP methods to the class, Functional programming in PHP5

More serious example About functional programming in PHP5 without waiting for PHP7 which BTW is still not enough functional.

I prepared few examples about refactoring PHP code from class to functional programming.

It’s another perspective, which give many benefits with going to the way where class is implemented as function with value typed over interface.

Refactoring PHP methods to the class, Functional programming in PHP5, see below more details …

Class instead method

function isLocalhost()

Class which is implemented by interface to say about data type

class IsLocalhost implements BooleanValue
public function __construct()

Interface which define data type

The interface BooleanValue describe which type of value is the result, which made function in PHP Class

It is not so nice to write a lot to have result which is in Python or NodeJS so easy to write, but this is PHP, he love talking a lot 😉
Movie about differents beetween Python and PHP

How You see I am using similary to way like with Design Patterns – Decorator, to dynamically add new functionality to class instances.

First Usage To Show Info about Host

usage with function ‘echo‘ as command

Extended Info, more easy to handle as class

usage with class SayThatIsLocalhost instead of ‘echo‘ command, try to catch if something will be wrong

Moving simple function to Class

With the next class instead of simple php function such ‘echo‘, we have possibilities to extend whole system from many sites, without border such:

  • simple php functions
  • static method or variables
  • variables

With example class SayThatIsLocalhost it is possible to easy extending the code, going forward by creating next classes. It is too easy to reause because function is just responisbile for one part of code, so simple such show some text.

What if is necessary to do translation?

just use another namespace, library, file during autoloading:

Or by using next Class to recognize which language is using by user:

If will by some problem with empty Value $language, The PHP environment is responsibly to say about problems with data types. I showed differences based on examples between strong typing, which make more comfortable coding, testing and refactoring what give benefits above a standard coding.

To be honest, it’s not the final version and not the best solution, that why I am waiting for a feedback from Your site and  from Web … site 😉


Author: Tom

I connect the expiriences with new ideas. Embedded System Software & Hardware Developer.

Disqus Comments (0)


Facebook Comments (0)