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

What's hot (20)

PPT
Function overloading(C++)
Ritika Sharma
 
PDF
Lambda Expressions in Java
Erhan Bagdemir
 
PDF
Java 8 by example!
Mark Harrison
 
PDF
Java 8 Lambda Expressions & Streams
NewCircle Training
 
PDF
Definitions of Functional Programming
Philip Schwarz
 
PDF
Functional go
Geison Goes
 
PDF
Python Programming - III. Controlling the Flow
Ranel Padon
 
PDF
Introduction to Python
Mohammed Sikander
 
PDF
Keywords in python
PushpakBhoge
 
PPTX
Java 8 presentation
Van Huong
 
PDF
Functional Python Webinar from October 22nd, 2014
Reuven Lerner
 
PPTX
Introduction To Programming with Python-1
Syed Farjad Zia Zaidi
 
PPT
JavaScript - Programming Languages course
yoavrubin
 
PDF
Functional Programming in Ruby
Alex Teut
 
DOCX
Differences between method overloading and method overriding
Pinky Anaya
 
PPTX
Functions in Python
Kamal Acharya
 
DOC
Storage classess of C progamming
Appili Vamsi Krishna
 
PDF
Control structures functions and modules in python programming
Srinivas Narasegouda
 
PDF
Python recursion
Prof. Dr. K. Adisesha
 
PPTX
Introduction To Programming with Python Lecture 2
Syed Farjad Zia Zaidi
 
Function overloading(C++)
Ritika Sharma
 
Lambda Expressions in Java
Erhan Bagdemir
 
Java 8 by example!
Mark Harrison
 
Java 8 Lambda Expressions & Streams
NewCircle Training
 
Definitions of Functional Programming
Philip Schwarz
 
Functional go
Geison Goes
 
Python Programming - III. Controlling the Flow
Ranel Padon
 
Introduction to Python
Mohammed Sikander
 
Keywords in python
PushpakBhoge
 
Java 8 presentation
Van Huong
 
Functional Python Webinar from October 22nd, 2014
Reuven Lerner
 
Introduction To Programming with Python-1
Syed Farjad Zia Zaidi
 
JavaScript - Programming Languages course
yoavrubin
 
Functional Programming in Ruby
Alex Teut
 
Differences between method overloading and method overriding
Pinky Anaya
 
Functions in Python
Kamal Acharya
 
Storage classess of C progamming
Appili Vamsi Krishna
 
Control structures functions and modules in python programming
Srinivas Narasegouda
 
Python recursion
Prof. Dr. K. Adisesha
 
Introduction To Programming with Python Lecture 2
Syed Farjad Zia Zaidi
 

Viewers also liked (20)

PPTX
Quick look in Reactive Extensions
johnlvidal
 
PPTX
Presentation1
Kamalakanta Sahoo
 
PPT
Route Auchan Taverny
Philippe Fabre
 
PDF
K. Dharma Provissional Certi....
Dharmalingam Kaliyaperumal
 
PDF
Reprogramación cronograma EUS semestre 2015 2
Coordinación Académica Escuela de Educación
 
DOC
Resume alejandro garcia-de-frenza
Alejandro Garcia
 
PDF
open messenger-messaging-for-livelihood-development
digitalvisionoxfam
 
PDF
0 a045g formation-construction-de-typologie-et-modeles-d-association-avec-ibm...
CERTyou Formation
 
PDF
Requisitos para Petición de Grado pregrado ucv
Coordinación Académica Escuela de Educación
 
DOCX
Siklus estrus
InXs Bg
 
PDF
sf2-RecordOfAchievement
Charmi Jilka
 
PPT
1 introducao a quimica
Arilson Prata
 
PDF
Coservit - LeadSeed solution sheet
Marketo
 
PPTX
Siemens - SucessFactors Suite Overview
Syed Faisal Hasan
 
PDF
Evolution of Performance Management: Oracle 12c adaptive optimizations - ukou...
Nelson Calero
 
PDF
Certificados Locutor Acta 15
Facultad de Humanidades y Educación
 
PDF
Certificados Locutor Acta 14
Facultad de Humanidades y Educación
 
PPTX
L'ere du Marketer Geek
Marketo
 
PDF
Gestão de fluxo de caixa
Roberto Toledo
 
PPTX
Glosario
paulamglez
 
Quick look in Reactive Extensions
johnlvidal
 
Presentation1
Kamalakanta Sahoo
 
Route Auchan Taverny
Philippe Fabre
 
K. Dharma Provissional Certi....
Dharmalingam Kaliyaperumal
 
Reprogramación cronograma EUS semestre 2015 2
Coordinación Académica Escuela de Educación
 
Resume alejandro garcia-de-frenza
Alejandro Garcia
 
open messenger-messaging-for-livelihood-development
digitalvisionoxfam
 
0 a045g formation-construction-de-typologie-et-modeles-d-association-avec-ibm...
CERTyou Formation
 
Requisitos para Petición de Grado pregrado ucv
Coordinación Académica Escuela de Educación
 
Siklus estrus
InXs Bg
 
sf2-RecordOfAchievement
Charmi Jilka
 
1 introducao a quimica
Arilson Prata
 
Coservit - LeadSeed solution sheet
Marketo
 
Siemens - SucessFactors Suite Overview
Syed Faisal Hasan
 
Evolution of Performance Management: Oracle 12c adaptive optimizations - ukou...
Nelson Calero
 
Certificados Locutor Acta 15
Facultad de Humanidades y Educación
 
Certificados Locutor Acta 14
Facultad de Humanidades y Educación
 
L'ere du Marketer Geek
Marketo
 
Gestão de fluxo de caixa
Roberto Toledo
 
Glosario
paulamglez
 
Ad

Similar to PHP = PHunctional Programming (20)

PPTX
Functional programming for the Advanced Beginner
Luis Atencio
 
PPTX
Functional programming in python
Edward D. Weinberger
 
PDF
Functional programming in python
Edward D. Weinberger
 
PDF
Python interview questions and answers
kavinilavuG
 
DOCX
Python interview questions and answers
RojaPriya
 
PDF
Functional Programming In PHP I
Umut IŞIK
 
PDF
Twins: Object Oriented Programming and Functional Programming
RichardWarburton
 
PPTX
Functions in Python Syntax and working .
tarunsharmaug23
 
PDF
Introduction to functional programming
Konrad Szydlo
 
KEY
Exciting JavaScript - Part I
Eugene Lazutkin
 
PPT
Basics of cpp
vinay chauhan
 
PDF
Python functions
Prof. Dr. K. Adisesha
 
PPTX
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
usha raj
 
PDF
PHP7: Hello World!
Pavel Nikolov
 
PPTX
Functions
Gaurav Subham
 
PPTX
Python and You Series
Karthik Prakash
 
PDF
3-Python Functions.pdf in simple.........
mxdsnaps
 
PPT
PHP Fuctions.ppt,IT CONTAINS PHP INCLUDE FUNCTION
ashokkumar910878
 
PPTX
use of Functions to write python program.pptx
rahulsinghsikarwar2
 
PPTX
Learn more about the concepts Functions of Python
PrathamKandari
 
Functional programming for the Advanced Beginner
Luis Atencio
 
Functional programming in python
Edward D. Weinberger
 
Functional programming in python
Edward D. Weinberger
 
Python interview questions and answers
kavinilavuG
 
Python interview questions and answers
RojaPriya
 
Functional Programming In PHP I
Umut IŞIK
 
Twins: Object Oriented Programming and Functional Programming
RichardWarburton
 
Functions in Python Syntax and working .
tarunsharmaug23
 
Introduction to functional programming
Konrad Szydlo
 
Exciting JavaScript - Part I
Eugene Lazutkin
 
Basics of cpp
vinay chauhan
 
Python functions
Prof. Dr. K. Adisesha
 
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
usha raj
 
PHP7: Hello World!
Pavel Nikolov
 
Functions
Gaurav Subham
 
Python and You Series
Karthik Prakash
 
3-Python Functions.pdf in simple.........
mxdsnaps
 
PHP Fuctions.ppt,IT CONTAINS PHP INCLUDE FUNCTION
ashokkumar910878
 
use of Functions to write python program.pptx
rahulsinghsikarwar2
 
Learn more about the concepts Functions of Python
PrathamKandari
 
Ad

More from Luis Atencio (7)

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

Recently uploaded (20)

PPTX
Get Started with Maestro: Agent, Robot, and Human in Action – Session 5 of 5
klpathrudu
 
PDF
UITP Summit Meep Pitch may 2025 MaaS Rebooted
campoamor1
 
PDF
AI Prompts Cheat Code prompt engineering
Avijit Kumar Roy
 
PPTX
Function & Procedure: Function Vs Procedure in PL/SQL
Shani Tiwari
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PDF
Best Web development company in india 2025
Greenusys
 
PDF
Latest Capcut Pro 5.9.0 Crack Version For PC {Fully 2025
utfefguu
 
PPTX
UI5con_2025_Accessibility_Ever_Evolving_
gerganakremenska1
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PDF
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
PPTX
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
PDF
Is Framer the Future of AI Powered No-Code Development?
Isla Pandora
 
PDF
Technical-Careers-Roadmap-in-Software-Market.pdf
Hussein Ali
 
PDF
Why is partnering with a SaaS development company crucial for enterprise succ...
Nextbrain Technologies
 
PDF
MiniTool Power Data Recovery 8.8 With Crack New Latest 2025
bashirkhan333g
 
PPTX
Transforming Insights: How Generative AI is Revolutionizing Data Analytics
LetsAI Solutions
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PPTX
Smart Doctor Appointment Booking option in odoo.pptx
AxisTechnolabs
 
PPTX
BB FlashBack Pro 5.61.0.4843 With Crack Free Download
cracked shares
 
PDF
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
Get Started with Maestro: Agent, Robot, and Human in Action – Session 5 of 5
klpathrudu
 
UITP Summit Meep Pitch may 2025 MaaS Rebooted
campoamor1
 
AI Prompts Cheat Code prompt engineering
Avijit Kumar Roy
 
Function & Procedure: Function Vs Procedure in PL/SQL
Shani Tiwari
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
Best Web development company in india 2025
Greenusys
 
Latest Capcut Pro 5.9.0 Crack Version For PC {Fully 2025
utfefguu
 
UI5con_2025_Accessibility_Ever_Evolving_
gerganakremenska1
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
Is Framer the Future of AI Powered No-Code Development?
Isla Pandora
 
Technical-Careers-Roadmap-in-Software-Market.pdf
Hussein Ali
 
Why is partnering with a SaaS development company crucial for enterprise succ...
Nextbrain Technologies
 
MiniTool Power Data Recovery 8.8 With Crack New Latest 2025
bashirkhan333g
 
Transforming Insights: How Generative AI is Revolutionizing Data Analytics
LetsAI Solutions
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
Smart Doctor Appointment Booking option in odoo.pptx
AxisTechnolabs
 
BB FlashBack Pro 5.61.0.4843 With Crack Free Download
cracked shares
 
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 

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