SlideShare a Scribd company logo
By Luis Atencio (@luijar)
PHP = PHunctional Programming
Northeast
PHP
Conference 2016
What? Functional... PHP?
You don’t need to understand
Category Theory to grok FP
Agenda
1. Understand the FP stuff
2. Function composition and declarative coding
3. Currying
4. Functors
5. Monads
6. Cool FP libs for PHP
PHP = PHunctional Programming
PHP functions became instances of
Closure
Mathematical-like computing
ƛx.x + 1
The birth of the anonymous function!
(ƛx.x + 1)3 = 4
(ƛx.x + 1)((ƛy.y + 2))3 = 6
What did we learn from the Maths?
Pure Functions
• No side effects!
• Clear contracts input and output
• Self-documenting
• Stateless
Immutability
• Can’t change the contents of something once it’s been initialized
Higher-order functions
• Pass functions into other functions
• Return functions from other functions
What is a side effect?
A function execution that impacts its outer scope. The effect is more
detrimental when it’s the global scope
Pure Functions
A function without side effects that returns the same result on
same input
Immutability
• Look at immutability through the consistent (repeatable) execution
of pure functions
• Most bugs originate from data issues
• Functions are (represent) immutable values
• Very limited support in PHP
Higher-order functions
• Pass functions to other functions
• Return functions from other functions
• Lazy evaluation
Variable functions
• If a variable has parenthesis appended to it, PHP will try to invoke
it
• Can be passed in by name (string) or reference
• Will not work with language constructs:
• echo
• print
• unset
• isset
• empty
Composition vs Inheritance
Composition vs Inheritance2
Adding new behavior
is easy
Functions are first-class in PHP
The Closure class was added in PHP 5.3.0
Everything is an object under the hood
Syntactic Sugar
Towards more functional code
PHP 4.0.6 introduced (but they are not pure!) to eliminate looping!
• array_map()
• array_filter()
• array_reduce()
Application State: OO
In OO you move state by passing objects around and invoking
methods on those objects. In FP you pass state to the functions and
combine them to move/transform it.
ObjectA
ObjectC
ObjectB
ObjectD
Application State: FP
In FP you pass state to the functions and combine them to
move/transform it.
FuncA
FuncC
FuncB
FuncD
FP vs OO
Declarative vs Imperative
Functions vs Objects
Stateless vs Stateful
Mutable vs Immutable
Declarative
• Describe WHAT a program does
• Not HOW to do it
Unix pipeline
SQL
Declarative2
Using PRamda Functional PHP Library
https://github.com/kapolos/pramda
Lambda Expressions
Arrow functions RFC under discussion
https://wiki.php.net/rfc/arrow_functions
Function composition
Declarative style + modularity
Function composition
The composition of functions f and g is another function that takes the
result of g and pass it to f:
f o g = f( g(x) )
f g Input: AOutput: C
A -> BB -> C
B
Function composition2
Examples:
This is where the term “Composer” comes from
Function composition3
It’s just the inverse of PIPE!
Point-free style!
Currying
• Composition requires we use single argument functions
• Partially evaluate a function as a sequence of steps providing one
argument at a time
• PHP uses eager function evaluation
function f(a, b) { … }
f a
evaluating: returns:
( )
Currying2
Transforms a multi-argument function into several single-arity functions
function f(a, b) { … }
curry(f) = function (a, b) {
return function (a) {
return function (b) {
...
}
}
}
wait to be invoked
Currying3
Example:
Currying + Composition
Example:
What about errors?
Map-able container
Containers are not new
Generalization
Protecting access to data
?
Mapping a value to a container
strtolower
HELLO
HELLO
Map function
hello
wrap
Container
HELLO Lift This is known as a Functor!!
Option Type
Intended for cases when you might want to return a value—like an
object, or (optionally) not—like null.
https://github.com/schmittjoh/php-option
vs
Option Type2
What to do with nested types?
Introducing flatMap()
This is known as a Monad!!
Reactive Programming
The Observable type
Treat any type of data (of any size) as a composable stream. Makes
use of the Observer pattern
More observables
Business
Logic
Orchestrate
Functional, Async computing
https://github.com/ReactiveX/RxPHP
Conclusion
PHP = FP + OO
“..FP in the small... OO in the large...”
- Michael Feathers
Resources
Functional PHP
Resource https://leanpub.com/functional-php
Free to read!!!
Functional Programming in JavaScript
Resource https://www.manning.com/atencio
Get on Amazon
RxJS in Action
Resource https://www.manning.com/books
/rxjs-in-action
Get on Manning.com
@luijar

More Related Content

PPT
3 Function Overloading
PDF
Functional programming
PDF
Some basic FP concepts
PPTX
Dev Concepts: Functional Programming
PPTX
Functional programming
PDF
Python functional programming
PDF
Aaa ped-2- Python: Basics
PPTX
Functions in Python
3 Function Overloading
Functional programming
Some basic FP concepts
Dev Concepts: Functional Programming
Functional programming
Python functional programming
Aaa ped-2- Python: Basics
Functions in Python

What's hot (20)

PPT
Function overloading(C++)
PDF
Lambda Expressions in Java
PDF
Java 8 by example!
PDF
Java 8 Lambda Expressions & Streams
PDF
Definitions of Functional Programming
PDF
Functional go
PDF
Python Programming - III. Controlling the Flow
PDF
Introduction to Python
PDF
Keywords in python
PPTX
Java 8 presentation
PDF
Functional Python Webinar from October 22nd, 2014
PPTX
Introduction To Programming with Python-1
PPT
JavaScript - Programming Languages course
PDF
Functional Programming in Ruby
DOCX
Differences between method overloading and method overriding
PPTX
Functions in Python
DOC
Storage classess of C progamming
PDF
Control structures functions and modules in python programming
PDF
Python recursion
PPTX
Introduction To Programming with Python Lecture 2
Function overloading(C++)
Lambda Expressions in Java
Java 8 by example!
Java 8 Lambda Expressions & Streams
Definitions of Functional Programming
Functional go
Python Programming - III. Controlling the Flow
Introduction to Python
Keywords in python
Java 8 presentation
Functional Python Webinar from October 22nd, 2014
Introduction To Programming with Python-1
JavaScript - Programming Languages course
Functional Programming in Ruby
Differences between method overloading and method overriding
Functions in Python
Storage classess of C progamming
Control structures functions and modules in python programming
Python recursion
Introduction To Programming with Python Lecture 2
Ad

Viewers also liked (20)

PPTX
Quick look in Reactive Extensions
PPTX
Presentation1
PPT
Route Auchan Taverny
PDF
K. Dharma Provissional Certi....
PDF
Reprogramación cronograma EUS semestre 2015 2
DOC
Resume alejandro garcia-de-frenza
PDF
open messenger-messaging-for-livelihood-development
PDF
0 a045g formation-construction-de-typologie-et-modeles-d-association-avec-ibm...
PDF
Requisitos para Petición de Grado pregrado ucv
DOCX
Siklus estrus
PDF
sf2-RecordOfAchievement
PPT
1 introducao a quimica
PDF
Coservit - LeadSeed solution sheet
PPTX
Siemens - SucessFactors Suite Overview
PDF
Evolution of Performance Management: Oracle 12c adaptive optimizations - ukou...
PDF
Certificados Locutor Acta 15
PDF
Certificados Locutor Acta 14
PPTX
L'ere du Marketer Geek
PDF
Gestão de fluxo de caixa
PPTX
Glosario
Quick look in Reactive Extensions
Presentation1
Route Auchan Taverny
K. Dharma Provissional Certi....
Reprogramación cronograma EUS semestre 2015 2
Resume alejandro garcia-de-frenza
open messenger-messaging-for-livelihood-development
0 a045g formation-construction-de-typologie-et-modeles-d-association-avec-ibm...
Requisitos para Petición de Grado pregrado ucv
Siklus estrus
sf2-RecordOfAchievement
1 introducao a quimica
Coservit - LeadSeed solution sheet
Siemens - SucessFactors Suite Overview
Evolution of Performance Management: Oracle 12c adaptive optimizations - ukou...
Certificados Locutor Acta 15
Certificados Locutor Acta 14
L'ere du Marketer Geek
Gestão de fluxo de caixa
Glosario
Ad

Similar to PHP = PHunctional Programming (20)

PPTX
Functional programming for the Advanced Beginner
PPTX
Functional programming in python
PDF
Functional programming in python
PDF
Python interview questions and answers
DOCX
Python interview questions and answers
PDF
Functional Programming In PHP I
PDF
Twins: Object Oriented Programming and Functional Programming
PPTX
Functions in Python Syntax and working .
PDF
Introduction to functional programming
KEY
Exciting JavaScript - Part I
PPT
Basics of cpp
PDF
Python functions
PPTX
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
PDF
PHP7: Hello World!
PPTX
Functions
PPTX
Python and You Series
PDF
3-Python Functions.pdf in simple.........
PPT
PHP Fuctions.ppt,IT CONTAINS PHP INCLUDE FUNCTION
PPTX
use of Functions to write python program.pptx
PPTX
Learn more about the concepts Functions of Python
Functional programming for the Advanced Beginner
Functional programming in python
Functional programming in python
Python interview questions and answers
Python interview questions and answers
Functional Programming In PHP I
Twins: Object Oriented Programming and Functional Programming
Functions in Python Syntax and working .
Introduction to functional programming
Exciting JavaScript - Part I
Basics of cpp
Python functions
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
PHP7: Hello World!
Functions
Python and You Series
3-Python Functions.pdf in simple.........
PHP Fuctions.ppt,IT CONTAINS PHP INCLUDE FUNCTION
use of Functions to write python program.pptx
Learn more about the concepts Functions of Python

More from Luis Atencio (7)

PDF
379008-rc217-functionalprogramming
PDF
DZone_RC_RxJS
PPTX
Luis Atencio on RxJS
PPTX
Thinking Functionally with JavaScript
PPTX
Functional Programming in JavaScript by Luis Atencio
PPTX
Java script Techniques Part I
PPTX
Luis atencio on_git
379008-rc217-functionalprogramming
DZone_RC_RxJS
Luis Atencio on RxJS
Thinking Functionally with JavaScript
Functional Programming in JavaScript by Luis Atencio
Java script Techniques Part I
Luis atencio on_git

Recently uploaded (20)

PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
How Creative Agencies Leverage Project Management Software.pdf
PPTX
ai tools demonstartion for schools and inter college
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PPTX
history of c programming in notes for students .pptx
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PPTX
L1 - Introduction to python Backend.pptx
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PPTX
Operating system designcfffgfgggggggvggggggggg
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Digital Strategies for Manufacturing Companies
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
System and Network Administraation Chapter 3
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
How Creative Agencies Leverage Project Management Software.pdf
ai tools demonstartion for schools and inter college
Design an Analysis of Algorithms II-SECS-1021-03
How to Choose the Right IT Partner for Your Business in Malaysia
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
history of c programming in notes for students .pptx
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
L1 - Introduction to python Backend.pptx
Design an Analysis of Algorithms I-SECS-1021-03
ManageIQ - Sprint 268 Review - Slide Deck
Operating system designcfffgfgggggggvggggggggg
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
2025 Textile ERP Trends: SAP, Odoo & Oracle
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Digital Strategies for Manufacturing Companies
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Odoo Companies in India – Driving Business Transformation.pdf
System and Network Administraation Chapter 3
Adobe Illustrator 28.6 Crack My Vision of Vector Design

PHP = PHunctional Programming

Editor's Notes

  • #3: Didn’t we just become fully OO with 5.3? Functional Programming is the extensive use of functions to move the application from one state to the next
  • #5: Objective: Understand PHP bettter
  • #7: This gives rise to HO functions. Since objects can be passed around and returned
  • #8: Everything can be represented in the context of lambda expressions In school, we’re taught about Turing machines and Von Neumann Model
  • #10: Pure functions: count. Exceptions are thrown, printing to the console Is time() a pure function?
  • #11: Pure functions: count. Is time() a pure function?
  • #12: const cannot be used to conditionally define constants. To define a global constant, it has to be used in the outermost scope: if (...) { const FOO = 'BAR'; // invalid } // but if (...) { define('FOO', 'BAR'); // valid } const accepts a static scalar (number, string or other constant like true, false, null, __FILE__), whereas define() takes any expression. Since PHP 5.6 constant expressions are allowed in const as well: const BIT_5 = 1 << 5; // valid since PHP 5.6, invalid previously define('BIT_5', 1 << 5); // always valid const takes a plain constant name, whereas define() accepts any expression as name. This allows to do things like this: for ($i = 0; $i < 32; ++$i) { define('BIT_' . $i, 1 << $i); } consts are always case sensitive, whereas define() allows you to define case insensitive constants by passing true as the third argument const simply reads nicer. It's a language construct instead of a function and also is consistent with how you define constants in classes. const defines a constant in the current namespace, while define() has to be passed the full namespace name: namespace A\B\C; // To define the constant A\B\C\FOO: const FOO = 'BAR'; define('A\B\C\FOO', 'BAR'); Since PHP 5.6 const constants can also be arrays, while define() does not support arrays yet. However arrays will be supported for both cases in PHP 7. const FOO = [1, 2, 3]; // valid in PHP 5.6 define('FOO', [1, 2, 3]); // invalid in PHP 5.6, valid in PHP 7.0 As consts are language constructs and defined at compile time they are a bit faster than define()s.
  • #15: Adding a new strategy involves creating a new class. Ex. safeDivide
  • #16: FP makes patterns disappear
  • #19: No consistent API Cumbersome and verbose to use No currying Not immutable! They separate the loop away from your business logic
  • #22: This gives rise to HO functions. Since objects can be passed around and returned
  • #23: How to do it we let the compiler worry abo Variable functions ¶ PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth. Variable functions won't work with language constructs such as echo, print, unset(), isset(), empty(), include,require and the like. Utilize wrapper functions to make use of any of these constructs as variable functions.
  • #24: How to do it we let the compiler worry abo Variable functions ¶ PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth. Variable functions won't work with language constructs such as echo, print, unset(), isset(), empty(), include,require and the like. Utilize wrapper functions to make use of any of these constructs as variable functions.
  • #25: How to do it we let the compiler worry abo Variable functions ¶ PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth. Variable functions won't work with language constructs such as echo, print, unset(), isset(), empty(), include,require and the like. Utilize wrapper functions to make use of any of these constructs as variable functions.
  • #26: This gives rise to HO functions. Since objects can be passed around and returned
  • #29: This is also known as point-free style
  • #30: We can do this thanks to HO functions
  • #34: This gives rise to HO functions. Since objects can be passed around and returned
  • #37: Most errors are due to error in the data
  • #38: This is a functor
  • #39: You are documenting the fact that you’re using this type Option is a monad!
  • #40: You are documenting the fact that you’re using this type Option is a monad!
  • #41: Didn’t we just become fully OO with 5.3?
  • #46: Didn’t we just become fully OO with 5.3? Functional Programming is the extensive use of functions to move the application from one state to the next