Improving performance using PHP 7 enhancements
One trend that developers are taking advantage of is the use of anonymous functions. One classic problem, when dealing with anonymous functions, is to write them in such a way that any object can be bound to $this
and the function will still work. The approach used in PHP 5 code is to use bindTo()
. In PHP 7, a new method, call()
, was added, which offers similar functionality, but vastly improved performance.
How to do it...
To take advantage of call()
, execute an anonymous function in a lengthy loop. In this example, we will demonstrate an anonymous function, that scans through a log file, identifying IP addresses sorted by how frequently they appear:
- First, we define a
Application\Web\Access class
. In the constructor, we accept a filename as an argument. The log file is opened as anSplFileObject
and assigned to$this->log
:Namespace Application\Web; use Exception; use SplFileObject; class Access { const ERROR_UNABLE = 'ERROR: unable...