SlideShare a Scribd company logo
Being functional in PHP
David de Boer14 May 2016
Being functional in PHP (PHPDay Italy 2016)
functional
functions
y = f(x)
f: X → Y
functional programming
functional thinking
functional communication
not languages
Why should you care?
Being functional in PHP (PHPDay Italy 2016)
Being functional in PHP (PHPDay Italy 2016)
f(x)
Others
PHP
C++
C
Java
– Robert C. Martin
“There is a freight train barreling
down the tracks towards us, with
multi-core emblazoned on it; and
you’d better be ready by the time
it gets here.”
λ
closures
__invoke
2001 2009 2011 2012
array_map
array_filter
callable
Slim
Silex
middlewaresSymfony2
2013 2014 2015 2016
PSR-7
anonymous
classes
foreach
promises
futuresStackPHP
“The limits of my language
mean the limits of my world.”
– Ludwig Wittgenstein
I’m David
/ddeboer
@ddeboer_nl
Being functional in PHP (PHPDay Italy 2016)
Erlang: The Movie
Erlang
Concurrent
Passing messages
Fault-tolerant
Let’s begin$ brew install erlang
$ erl
Erlang/OTP 18 [erts-7.2.1] [source] [64-bit] [smp:4:4] [async-threads:
10] [hipe] [kernel-poll:false] [dtrace]
Eshell V7.2.1 (abort with ^G)
1>
on OS X
REPL
➊
<?php
$sum = 0;
for ($i = 1; $i <= 5; $i++) {
$sum = $sum + $i;
}
echo $sum;
// 15
-module(math).
-export([sum/1]).
sum(Number) ->
Sum = 0,
Numbers = lists:seq(1, Number),
lists:foreach(
fun(N) ->
Sum = Sum + N
end,
Numbers
),
Sum.
math:sum(5).
no return
keyword
** exception error: no match
of right hand side value 1
1> X = 5.
5
2> X.
5
3> X = X * 2.
** exception error: no match of right hand side value 10
4> 5 = 10.
** exception error: no match of right hand side value 10
but isn’t
looks like
assignment
1> lists:sum(lists:seq(1, 5)).
15
➋
Imperative<?php
$sum = 0;
for ($i = 1; $i <= 5; $i++) {
$sum = $sum + $i;
}
iteration
keeps
changing
-module(math2).
-export([sum2/1]).
sum2(Number) ->
List = lists:seq(1, Number),
sum2(List, 0).
sum2([], Sum) -> Sum;
sum2([H|T], Sum) -> sum2(T, H + Sum).
3> math2:sum(5).
15
empty list
separate head from tail recurse
pattern
matches
generate list
Declarative 1<?php
// Declare a function!
function sum($x)
{
if ($x == 0) {
return $x;
}
return $x + sum($x - 1);
}
sum(5);
// still 15
$x never
changes
recursion
Declarative 2<?php
function sum2($number)
{
array_sum(range(1, $number));
}
echo sum2(5);
// yuuuup, 15 again
functionfunction
composition
Some history
Church Von Neumann
declarative imperative
Being functional in PHP (PHPDay Italy 2016)
A lot of our code is about the
hardware it runs on
But programmers should worry

about the conceptual problem domain
Recursion-module(math).
-export([fac/1]).
fac(0) -> 1;
fac(N) -> N * fac(N - 1).
1> math:fac(9).
362880
Recursion fail-module(math).
-export([fac/1]).
fac(0) -> 1;
fac(N) -> N * fac(N - 1).
%%fac(9) = 9 * fac(9 - 1)
%% = 9 * 8 * fac(8 - 1)
%% = 9 * 8 * 7 * fac(7 - 1)
%% = 9 * 8 * 7 * 6 * fac(6 - 1)
%% = 9 * 8 * 7 * 6 * 5 * fac(5 -1)
%% = 9 * 8 * 7 * 6 * 5 * 4 * fac(4 - 1)
%% = 9 * 8 * 7 * 6 * 5 * 4 * 3 * fac(3 - 1)
%% = 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * fac(2 - 1)
%% = 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 * fac(1 - 1)
%% = 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 * 1
%% = 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1
%% = 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2
%% = 9 * 8 * 7 * 6 * 5 * 4 * 6
%% = 9 * 8 * 7 * 6 * 5 * 24
%% = 9 * 8 * 7 * 6 * 120
%% = 9 * 8 * 7 * 720
%% = 9 * 8 * 5040
%% = 9 * 40320
%% = 362880
10 terms in
memory
Tail recursion-module(math).
-export([tail_fac/1]).
tail_fac(N) -> tail_fac(N, 1).
tail_fac(0, Acc) -> Acc;
tail_fac(N, Acc) -> tail_fac(N - 1, N * Acc).
tail_fac(9) = tail_fac(9, 1).
tail_fac(9, 1) = tail_fac(9 - 1, 9 * 1).
tail_fac(8, 9) = tail_fac(8 - 1, 8 * 9).
tail_fac(7, 72) = tail_fac(7 - 1, 7 * 72).
tail_fac(6, 504) = tail_fac(6 - 1, 6 * 504).
tail_fac(5, 3024) = tail_fac(5 - 1, 5 * 3024).
…
tail_fac(0, 362880) = 362880
do calculation
before recursing
➌
Being functional in PHP (PHPDay Italy 2016)
$object->setFoo(5);
$value = $object->getFoo();
no
return
value
no input
value
$object->setFoo(5);
$value = $object->getFoo();
$object->setFoo('Change of state!');
$value = $object->getFoo();
no
return
value
no input
value
same argument,
different return value
No side-effects
A pure function
does not rely on data outside itself
does not change data outside itself
Object orientation
Solve problems with objects
Objects have internal state
Modify state through methods
With side-effectsclass Todo
{
public $status = 'todo';
}
function finish(Todo $task)
{
$task->status = 'done';
}
$uhoh = new Todo();
$uhoh2 = $uhoh;
finish($uhoh);
echo $uhoh->status; // done
echo $uhoh2->status; // done???
No side-effectsclass Todo
{
public $status = 'todo';
}
function finish(Todo $task)
{
$copy = clone $task;
$copy->status = 'done';
return $copy;
}
$uhoh = new Todo();
$finished = finish($uhoh);
echo $finished->status; // done
echo $uhoh->status; // todo
cloning is
cheap
Some state 

must change
Read/write database
Get user input
Current date and time
Random values (security)
Immutable objects
PSR-7 HTTP messages
Domain value objects
DateTimeImmutable
Service objects
➍
Higher-order functions
Functions are values
so they can be arguments
and return values
$names = ['Billy', 'Bob', 'Thornton'];
$anonymise = anonymise('sha256');
var_dump(array_map($anonymise, $names));
// array(3) {
// [0]=>
// string(64) "85eea4a0285dcb11cceb68f39df10d1aa132567dec49b980345142f09f4cb05e"
// [1]=>
// string(64) "cd9fb1e148ccd8442e5aa74904cc73bf6fb54d1d54d333bd596aa9bb4bb4e961"
// [2]=>
// string(64) "d7034215823c40c12ec0c7aaff96db94a0e3d9b176f68296eb9d4ca7195c958e"
// }
using PHP built-ins
$names = ['Billy', 'Bob', 'Thornton'];
$anonymise = anonymise('sha256');
var_dump(array_map($anonymise, $names));
// array(3) {
// [0]=>
// string(64) "85eea4a0285dcb11cceb68f39df10d1aa132567dec49b980345142f09f4cb05e"
// [1]=>
// string(64) "cd9fb1e148ccd8442e5aa74904cc73bf6fb54d1d54d333bd596aa9bb4bb4e961"
// [2]=>
// string(64) "d7034215823c40c12ec0c7aaff96db94a0e3d9b176f68296eb9d4ca7195c958e"
// }
function anonymise($algorithm)
{
return function ($value) use ($algorithm) {
return hash($algorithm, $value);
};
}
higher-order function
closure
using PHP built-ins
function as value
function as argument
Middleware<?php
use PsrHttpMessageRequestInterface;
function add_header($header, $value)
{
return function (callable $handler) use ($header, $value) {
return function (
RequestInterface $request,
array $options
) use ($handler, $header, $value) {
$request = $request->withHeader($header, $value);
return $handler($request, $options);
};
};
}
$myStack = (new MiddlewareStack())
->push(add_header('Silly-Header', 'and its value'));
call next

in stack
immutable
higher-order function
Middleware<?php
use PsrHttpMessageServerRequestInterface as Request;
use PsrHttpMessageResponseInterface as Response;
$app = new SlimApp();
$app->add(function (Request $request, Response $response, callable $next) {
$response->getBody()->write('Hey there, ');
$response = $next($request, $response);
$response->getBody()->write('up?');
return $response;
});
$app->get('/', function ($request, $response, $args) {
$response->getBody()->write('what’s');
return $response;
});
$app->run();
// Hey there, what’s up?
stream is not 

immutable
before
after
➎
Composition over
inheritance
Being functional in PHP (PHPDay Italy 2016)
Service objects<?php
namespace SymfonyComponentSecurityCore;
interface SecurityContextInterface
{
public function getToken();
public function isGranted($attributes, $object = null);
}
Service objects<?php
namespace SymfonyComponentSecurityCoreAuthenticationTokenStorage;
interface TokenStorageInterface
{
public function getToken();
}
namespace SymfonyComponentSecurityCoreAuthorization;
interface AuthorizationCheckerInterface
{
public function isGranted($attributes, $object = null);
}
single function
Single responsibility
taken to its
logical conclusion
You may not need
all those patterns
Take-aways
Reduce and isolate side-effects
Create immutable value objects
Be declarative
More?
Thanks!
https://joind.in/talk/bc26a
@ddeboer_nl

More Related Content

PDF
Being functional in PHP (DPC 2016)
PPTX
Category theory, Monads, and Duality in the world of (BIG) Data
PDF
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
PDF
Advanced python
PDF
Opaque Pointers Are Coming
PDF
PHP Performance Trivia
PDF
Imugi: Compiler made with Python
PDF
Talk - Query monad
Being functional in PHP (DPC 2016)
Category theory, Monads, and Duality in the world of (BIG) Data
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
Advanced python
Opaque Pointers Are Coming
PHP Performance Trivia
Imugi: Compiler made with Python
Talk - Query monad

What's hot (19)

PDF
Nikita Popov "What’s new in PHP 8.0?"
PDF
ES6 - Next Generation Javascript
PPTX
ES6 in Real Life
PDF
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
PDF
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
PDF
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
PDF
Java Class Design
PDF
PHP Language Trivia
PDF
Introducción a Elixir
PDF
Scalaz 8 vs Akka Actors
PPTX
Java 7, 8 & 9 - Moving the language forward
PPTX
Chapter 7 functions (c)
PDF
The best language in the world
PDF
ECMAScript 6
PDF
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
PDF
Programmation fonctionnelle en JavaScript
PDF
T3chFest 2016 - The polyglot programmer
PDF
Advanced Python, Part 1
PDF
Svitla talks 2021_03_25
Nikita Popov "What’s new in PHP 8.0?"
ES6 - Next Generation Javascript
ES6 in Real Life
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Java Class Design
PHP Language Trivia
Introducción a Elixir
Scalaz 8 vs Akka Actors
Java 7, 8 & 9 - Moving the language forward
Chapter 7 functions (c)
The best language in the world
ECMAScript 6
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Programmation fonctionnelle en JavaScript
T3chFest 2016 - The polyglot programmer
Advanced Python, Part 1
Svitla talks 2021_03_25
Ad

Viewers also liked (14)

PDF
PHP 7 new engine
PDF
PHP 7 performances from PHP 5
PDF
PHP, Under The Hood - DPC
PPTX
Internet of Things With PHP
PPTX
PHP Optimization
PPTX
Php internal architecture
PPTX
PDF
PHP WTF
PPTX
Laravel Beginners Tutorial 1
KEY
Php 101: PDO
PPT
How PHP Works ?
PDF
[Community Open Camp] 給 PHP 開發者的 VS Code 指南
PDF
LaravelConf Taiwan 2017 開幕
PDF
Route 路由控制
PHP 7 new engine
PHP 7 performances from PHP 5
PHP, Under The Hood - DPC
Internet of Things With PHP
PHP Optimization
Php internal architecture
PHP WTF
Laravel Beginners Tutorial 1
Php 101: PDO
How PHP Works ?
[Community Open Camp] 給 PHP 開發者的 VS Code 指南
LaravelConf Taiwan 2017 開幕
Route 路由控制
Ad

Similar to Being functional in PHP (PHPDay Italy 2016) (20)

PDF
Being functional in PHP
PDF
Refactoring to Macros with Clojure
PDF
ClojureScript loves React, DomCode May 26 2015
PDF
Beauty and the beast - Haskell on JVM
PDF
Kotlin: forse è la volta buona (Trento)
ODP
Clojure: Practical functional approach on JVM
PPT
Cpp tutorial
PDF
All I know about rsc.io/c2go
PPT
CppTutorial.ppt
PDF
Kamil witecki asynchronous, yet readable, code
PPTX
ES6 is Nigh
PPTX
Groovy
PDF
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
KEY
Let's build a parser!
PPTX
Things about Functional JavaScript
PDF
Introduction to reactive programming & ReactiveCocoa
PPTX
MiamiJS - The Future of JavaScript
PDF
C c++-meetup-1nov2017-autofdo
PPT
Threaded Programming
Being functional in PHP
Refactoring to Macros with Clojure
ClojureScript loves React, DomCode May 26 2015
Beauty and the beast - Haskell on JVM
Kotlin: forse è la volta buona (Trento)
Clojure: Practical functional approach on JVM
Cpp tutorial
All I know about rsc.io/c2go
CppTutorial.ppt
Kamil witecki asynchronous, yet readable, code
ES6 is Nigh
Groovy
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
Let's build a parser!
Things about Functional JavaScript
Introduction to reactive programming & ReactiveCocoa
MiamiJS - The Future of JavaScript
C c++-meetup-1nov2017-autofdo
Threaded Programming

Recently uploaded (20)

PPT
Teaching material agriculture food technology
PDF
Electronic commerce courselecture one. Pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Modernizing your data center with Dell and AMD
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Unlocking AI with Model Context Protocol (MCP)
Teaching material agriculture food technology
Electronic commerce courselecture one. Pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
The AUB Centre for AI in Media Proposal.docx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Mobile App Security Testing_ A Comprehensive Guide.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Chapter 3 Spatial Domain Image Processing.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Modernizing your data center with Dell and AMD
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
NewMind AI Monthly Chronicles - July 2025
Encapsulation_ Review paper, used for researhc scholars
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
Unlocking AI with Model Context Protocol (MCP)

Being functional in PHP (PHPDay Italy 2016)