As you’ve probably noticed the way in which PHP calls it’s Higher-Order Functions is quite different from C#, Java and Swift. Basically PHP by default uses method calls that wrap the input as opposed to the C#, Java and Swift which rely on method chaining.

Here’s a Swift example of method chaining; the array of values is passed to the map using the chain dot syntax, similarly the result of that is chained to the sorted method, and ultimately to the forEach method.

Swift

Not only does this make it easier to understand the process flow, but also helps with the formatting of the processing block. In this example, I’ve pressed carriage return, after each method call in the chain in order to align their dots. This is a natural formatting feature in these languages.

### Here’s the equivalent in Java:

Java

Here’s the equivalent in PHP:

PHP

It’s broken up into a few separated commands, rsort(reverse sort) in particular must be separated from array_map, because array_map returns a new array, where as rsort sorts in place i.e. we can’t merge the two. However all is not lost, you can have something quite similar to Swift, Java and C# with a bit of PHP magic methods..

To achieve this we’re going to create a new class that extends ArrayObject and implements the magic method __call:

PHP

Quite a bit of code… but I promise it’s worth it. So after adding this class to your code, you can now rewrite the PHP version as follows:

PHP
OUTPUT : Chained Method Calls
18, 16, 14, 12, 10, 8, 6, 4, 2,

### Note:

• in PHP method chaining is done with -> instead .
• __call() magic method is triggered when invoking inaccessible methods in an object context.
• FArray can be called anything you like; and it acts as a stand-in for arrays. Similarly in the __call() method, you can name the methods anything you like; you could even choose to keep them the same as PHP’s default. i.e. instead of case map:, you could use case array_map` instead.

Happy coding…