Missing in PHP7: function references

This is the first post in my Missing in PHP7 series.

Over time, PHP has improved its capabilities with regards to functions. As of PHP 5.3 you can create anonymous functions and as of 5.4 you can use the callable type hint. However referencing a function still requires using a string.

Unlike in Languages such as Python, that do provide proper function references, tools provide no support for the PHP approach whatsoever. No autocompletion or type checking in your IDE. No warnings from static code analysis tools. No “find usages” support.

Example

A common place where I run into this limitation is when I have a method that needs to return a modified version of an input array.

In such cases array_map and similar higher order functions are much nicer than creating additional state, doing an imperative loop and a bunch of assignments.

I consider the benefit of tool support big enough to prefer the following code over the above:

This does make the already hugely verbose array map even more verbose, and makes this one of these scenarios where I go “really PHP? really?” when I come across it.

Related: class references

A similar stringly-typed problem in PHP used to be creating mocks in PHPUnit. Which of course is not a PHP problem (in itself), though still something affecting many PHP projects.

This causes the same types of problems as the lack of function references. If you now rename or move KittenRepo, tools will not update these string references. If you try to find usages of the class, you’ll miss this one, unless you do string search.

Luckily PHP 5.5 introduced the class:: construct, which allows doing the following:

Where KittenRepo got imported with an use statement.

3 thoughts on “Missing in PHP7: function references”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.