O'Reilly logo

Functional PHP by Gilles Crettenand

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using composition to solve real issues

As an example, let's say that your boss comes in and wants you to produce a new report with the phone numbers of all users that have registered in the last 30 days. We assume that we have the following class representing our users. Obviously, a real class will store and return real data, but let us just define our API:

<?php 
 
class User { 
    public function phone(): string 
    { 
        return ''; 
    } 
 
    public function registration_date(): DateTime 
    { 
        return new DateTime(); 
    } 
} 
 
$users = [new User(), new User(), new User()]; // etc. 

Without any knowledge of functional programming, you might write something like this:

<?php class User { public function phone(): string { return ''; } public function registration_date(): DateTime { ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required