0% found this document useful (0 votes)
7 views79 pages

Pro Functional PHP Programming Application Development Strategies For Performance Optimization Concurrency Testability and Code Brevity Rob Aley Instant Download

The document is about 'Pro Functional PHP Programming' by Rob Aley, which focuses on application development strategies aimed at enhancing performance optimization, concurrency, testability, and code brevity. It covers key concepts of functional programming in PHP, advanced techniques, and strategies for building high-performance applications. The book also provides resources and supplementary materials for readers to access additional information and source code.

Uploaded by

amdurfaurekn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views79 pages

Pro Functional PHP Programming Application Development Strategies For Performance Optimization Concurrency Testability and Code Brevity Rob Aley Instant Download

The document is about 'Pro Functional PHP Programming' by Rob Aley, which focuses on application development strategies aimed at enhancing performance optimization, concurrency, testability, and code brevity. It covers key concepts of functional programming in PHP, advanced techniques, and strategies for building high-performance applications. The book also provides resources and supplementary materials for readers to access additional information and source code.

Uploaded by

amdurfaurekn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

Pro Functional Php Programming Application

Development Strategies For Performance


Optimization Concurrency Testability And Code
Brevity Rob Aley download
https://ebookbell.com/product/pro-functional-php-programming-
application-development-strategies-for-performance-optimization-
concurrency-testability-and-code-brevity-rob-aley-6729654

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Pro Functional Php Programming Rob Aley

https://ebookbell.com/product/pro-functional-php-programming-rob-
aley-6723920

Excel 2024 From Beginner To Pro A Comprehensive Guide To Excels Power


And Potential Functions Calculations Charts Pivot Tables With 3 Bonus
Robert Knowless

https://ebookbell.com/product/excel-2024-from-beginner-to-pro-a-
comprehensive-guide-to-excels-power-and-potential-functions-
calculations-charts-pivot-tables-with-3-bonus-robert-knowless-55513484

Excel 2022 From Basic To Advanced The Most Exhaustive Guide To Become
A Pro In Less Than 7 Days And Master All The Functions Formulas
Includes Practical Examples And Stepbystep Instructions George
Wahlberg
https://ebookbell.com/product/excel-2022-from-basic-to-advanced-the-
most-exhaustive-guide-to-become-a-pro-in-less-than-7-days-and-master-
all-the-functions-formulas-includes-practical-examples-and-stepbystep-
instructions-george-wahlberg-45108596

Pro Data Mashup For Power Bi Powering Up With Power Query And The M
Language To Find Load And Transform Data 1st Edition Adam Aspin

https://ebookbell.com/product/pro-data-mashup-for-power-bi-powering-
up-with-power-query-and-the-m-language-to-find-load-and-transform-
data-1st-edition-adam-aspin-44868580
Pro Php Refactoring Francesco Trucchia Jacopo Romei

https://ebookbell.com/product/pro-php-refactoring-francesco-trucchia-
jacopo-romei-46096178

Pro Django Marty Alchin

https://ebookbell.com/product/pro-django-marty-alchin-46553836

Pro Cryptography And Cryptanalysis With C20 Marius Iulian Mihailescu

https://ebookbell.com/product/pro-cryptography-and-cryptanalysis-
with-c20-marius-iulian-mihailescu-46619890

Pro Power Bi Theme Creation Json Stylesheets For Automated Dashboard


Formatting Converted Adam Aspin

https://ebookbell.com/product/pro-power-bi-theme-creation-json-
stylesheets-for-automated-dashboard-formatting-converted-adam-
aspin-46745534

Pro Sql Server 2022 Administration A Guide For The Modern Dba 3rd
Edition Peter A Carter

https://ebookbell.com/product/pro-sql-server-2022-administration-a-
guide-for-the-modern-dba-3rd-edition-peter-a-carter-47331394
Pro Functional
PHP Programming
Application Development Strategies for
Performance Optimization, Concurrency,
Testability, and Code Brevity

Rob Aley

www.allitebooks.com
Pro Functional PHP
Programming
Application Development Strategies for
Performance Optimization, Concurrency,
Testability, and Code Brevity

Rob Aley

www.allitebooks.com
Pro Functional PHP Programming: Application Development Strategies for Performance Optimization,
Concurrency, Testability, and Code Brevity
Rob Aley
Oxford, United Kingdom
ISBN-13 (pbk): 978-1-4842-2957-6 ISBN-13 (electronic): 978-1-4842-2958-3
DOI 10.1007/978-1-4842-2958-3
Library of Congress Control Number: 2017954985
Copyright © 2017 by Rob Aley
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are
not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Cover image by Freepik (www.freepik.com)
Managing Director: Welmoed Spahr
Editorial Director: Todd Green
Acquisitions Editor: Steve Anglin
Development Editor: Matthew Moodie
Technical Reviewer: Christopher Pitt
Coordinating Editor: Mark Powers
Copy Editor: Kim Wimpsett
Distributed to the book trade worldwide by Springer Science+Business Media New York,
233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail
[email protected], or visit www.springeronline.com. Apress Media, LLC is a California LLC
and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc).
SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail [email protected], or visit www.apress.com/
rights-permissions.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub via the book’s product page, located at www.apress.com/9781484229576. For more
detailed information, please visit www.apress.com/source-code.
Printed on acid-free paper

www.allitebooks.com
Contents at a Glance

About the Author�����������������������������������������������������������������������������������������������������xv


About the Technical Reviewer�������������������������������������������������������������������������������xvii
Acknowledgments��������������������������������������������������������������������������������������������������xix


■Part I: Functional Programming in PHP 7������������������������������������������� 1

■Chapter 1: Introduction����������������������������������������������������������������������������������������� 3

■Chapter 2: Functional Programming: Key Concepts�������������������������������������������� 11

■Chapter 3: Getting Started with Functional Patterns������������������������������������������� 45

■Chapter 4: Advanced Functional Techniques������������������������������������������������������� 69


■Part II: Application Development Strategies����������������������������������� 101

■Chapter 5: Strategies for High-Performance Applications�������������������������������� 103

■Chapter 6: Managing Business Logic with Functions���������������������������������������� 147
■■Chapter 7: Using Functional Programming in Objected-Oriented and
Procedural Applications������������������������������������������������������������������������������������ 165

■Chapter 8: Using Helper Libraries in Your Application�������������������������������������� 189

■Chapter 9: Processing Big Data with Functional PHP��������������������������������������� 213

■Chapter 10: Afterword��������������������������������������������������������������������������������������� 229

■Appendix A: Installing PHP and Libraries���������������������������������������������������������� 231

■Appendix B: Command-Line PHP����������������������������������������������������������������������� 247

■Appendix C: Functional Programming Resources��������������������������������������������� 269

Index��������������������������������������������������������������������������������������������������������������������� 289

iii

www.allitebooks.com
Contents

About the Author�����������������������������������������������������������������������������������������������������xv


About the Technical Reviewer�������������������������������������������������������������������������������xvii
Acknowledgments��������������������������������������������������������������������������������������������������xix


■Part I: Functional Programming in PHP 7������������������������������������������� 1

■Chapter 1: Introduction����������������������������������������������������������������������������������������� 3
Who Is This Book For?������������������������������������������������������������������������������������������������������ 3
What Is Functional Programming?����������������������������������������������������������������������������������� 3
Functional Programming Is SOLID���������������������������������������������������������������������������������������������������������� 6
What Are the Benefits of Functional Programming?������������������������������������������������������������������������������� 7
Who Uses Functional Programming, and Why?�������������������������������������������������������������������������������������� 7
Is Functional Programming “All or Nothing”?����������������������������������������������������������������������������������������� 8
Further Reading�������������������������������������������������������������������������������������������������������������������������������������� 8

Why Use PHP for Functional Programming?�������������������������������������������������������������������� 9


Why Not to Use PHP for Functional Programming������������������������������������������������������������ 9
PHP Versions������������������������������������������������������������������������������������������������������������������ 10
Conclusion���������������������������������������������������������������������������������������������������������������������� 10

■Chapter 2: Functional Programming: Key Concepts�������������������������������������������� 11
Examining State������������������������������������������������������������������������������������������������������������� 11
Mutability and Immutability�������������������������������������������������������������������������������������������� 14
Further Reading������������������������������������������������������������������������������������������������������������������������������������ 17

What Is a Function?�������������������������������������������������������������������������������������������������������� 17

www.allitebooks.com
■ Contents

Named Functions����������������������������������������������������������������������������������������������������������� 17
Variable Functions���������������������������������������������������������������������������������������������������������� 23
Language Constructs����������������������������������������������������������������������������������������������������� 24
Return Values����������������������������������������������������������������������������������������������������������������� 25
Lambda/Anonymous Functions�������������������������������������������������������������������������������������� 27
Higher-Order Functions�������������������������������������������������������������������������������������������������� 31
Scope����������������������������������������������������������������������������������������������������������������������������� 35
Further Reading������������������������������������������������������������������������������������������������������������������������������������ 37

State������������������������������������������������������������������������������������������������������������������������������� 37
Parameters/Arguments/Operands, Arity, and Variadic Functions����������������������������������� 38
Further Reading������������������������������������������������������������������������������������������������������������������������������������ 40

Closures������������������������������������������������������������������������������������������������������������������������� 40
Side Effects�������������������������������������������������������������������������������������������������������������������� 42
Referential Transparency������������������������������������������������������������������������������������������������ 42
Pure Functions��������������������������������������������������������������������������������������������������������������� 44
Lists and Collections������������������������������������������������������������������������������������������������������ 44
Further Reading������������������������������������������������������������������������������������������������������������������������������������ 44

Conclusion���������������������������������������������������������������������������������������������������������������������� 44

■Chapter 3: Getting Started with Functional Patterns������������������������������������������� 45
Map, Filter, and Reduce�������������������������������������������������������������������������������������������������� 45
Recursive Functions������������������������������������������������������������������������������������������������������� 48
Basic Recursion������������������������������������������������������������������������������������������������������������������������������������ 48

Implementing a Recursive Function������������������������������������������������������������������������������� 53


Partial Functions������������������������������������������������������������������������������������������������������������ 56
Functional Expressions�������������������������������������������������������������������������������������������������� 60
Functional Composition�������������������������������������������������������������������������������������������������� 62
Conclusion���������������������������������������������������������������������������������������������������������������������� 67

vi

www.allitebooks.com
■ Contents


■Chapter 4: Advanced Functional Techniques������������������������������������������������������� 69
Currying Functions��������������������������������������������������������������������������������������������������������� 69
The Mysterious Monad��������������������������������������������������������������������������������������������������� 72
What Is a Monad?����������������������������������������������������������������������������������������������������������� 72
The Maybe Monad�������������������������������������������������������������������������������������������������������������������������������� 76

Monad Axioms���������������������������������������������������������������������������������������������������������������� 79
Monad Axiom 1������������������������������������������������������������������������������������������������������������������������������������� 79
Monad Axiom 2������������������������������������������������������������������������������������������������������������������������������������� 79
Monad Axiom 3������������������������������������������������������������������������������������������������������������������������������������� 80

Testing the Monad Axioms��������������������������������������������������������������������������������������������� 80


Other Useful Monads������������������������������������������������������������������������������������������������������ 82
The IO Monad����������������������������������������������������������������������������������������������������������������� 86
Learn More About Monads��������������������������������������������������������������������������������������������� 88
Further Reading������������������������������������������������������������������������������������������������������������������������������������ 89

Recursion with Trampolines������������������������������������������������������������������������������������������� 89


Recursive Lambdas������������������������������������������������������������������������������������������������������������������������������ 92

The PHP Type System����������������������������������������������������������������������������������������������������� 93


Type Declarations����������������������������������������������������������������������������������������������������������� 95
Further Reading������������������������������������������������������������������������������������������������������������������������������������ 99

Summary������������������������������������������������������������������������������������������������������������������������ 99


■Part II: Application Development Strategies����������������������������������� 101

■Chapter 5: Strategies for High-Performance Applications�������������������������������� 103
Understanding and Measuring Performance���������������������������������������������������������������� 103
Measuring Performance: Profiling�������������������������������������������������������������������������������� 103
Manual Profiling����������������������������������������������������������������������������������������������������������� 104
Profiling Tools��������������������������������������������������������������������������������������������������������������� 106
Further Reading and Tools������������������������������������������������������������������������������������������������������������������ 107

vii

www.allitebooks.com
■ Contents

Low-Level Profiling������������������������������������������������������������������������������������������������������ 108


Further Reading���������������������������������������������������������������������������������������������������������������������������������� 108

Memoization����������������������������������������������������������������������������������������������������������������� 108
Further Reading���������������������������������������������������������������������������������������������������������������������������������� 120
The Downsides of Memoization���������������������������������������������������������������������������������������������������������� 120

Lazy Evaluation������������������������������������������������������������������������������������������������������������ 121


Further Reading���������������������������������������������������������������������������������������������������������������������������������� 121

Generators�������������������������������������������������������������������������������������������������������������������� 122
Further Reading���������������������������������������������������������������������������������������������������������������������������������� 130
The Downsides of Lazy Evaluation����������������������������������������������������������������������������������������������������� 130

Parallel Programming��������������������������������������������������������������������������������������������������� 131


Multithreaded Programming���������������������������������������������������������������������������������������� 141
Further Reading���������������������������������������������������������������������������������������������������������������������������������� 141

The Standard PHP Library (SPL)����������������������������������������������������������������������������������� 141


Further Reading���������������������������������������������������������������������������������������������������������������������������������� 145

Conclusion�������������������������������������������������������������������������������������������������������������������� 145

■Chapter 6: Managing Business Logic with Functions���������������������������������������� 147
Managing Business Logic�������������������������������������������������������������������������������������������� 147
Event-Based Programming������������������������������������������������������������������������������������������ 154
Further Reading���������������������������������������������������������������������������������������������������������������������������������� 156

Asynchronous PHP������������������������������������������������������������������������������������������������������� 163


Further Reading���������������������������������������������������������������������������������������������������������������������������������� 163

■■Chapter 7: Using Functional Programming in Objected-Oriented


and Procedural Applications����������������������������������������������������������������������������� 165
History of PHP Paradigms�������������������������������������������������������������������������������������������� 165
Further Reading���������������������������������������������������������������������������������������������������������������������������������� 166

PHP Is Not a Functional Language������������������������������������������������������������������������������� 166


Objects and Mutability������������������������������������������������������������������������������������������������� 168
Further Reading���������������������������������������������������������������������������������������������������������������������������������� 175

viii

www.allitebooks.com
■ Contents

Immutable Data with Objects��������������������������������������������������������������������������������������� 175


Object Properties As External State����������������������������������������������������������������������������� 180
Inline Impurities����������������������������������������������������������������������������������������������������������� 182
Procedural Programming Considerations��������������������������������������������������������������������� 186
Summary���������������������������������������������������������������������������������������������������������������������� 188

■Chapter 8: Using Helper Libraries in Your Application�������������������������������������� 189
How to Choose a Library���������������������������������������������������������������������������������������������� 189
Pick Libraries Apart������������������������������������������������������������������������������������������������������ 190
Libraries Based on Ramda������������������������������������������������������������������������������������������� 190
Pramda����������������������������������������������������������������������������������������������������������������������������������������������� 190
Phamda���������������������������������������������������������������������������������������������������������������������������������������������� 196

Libraries Based on Underscore������������������������������������������������������������������������������������ 199


Underscore.php (1)����������������������������������������������������������������������������������������������������������������������������� 199
Underscore����������������������������������������������������������������������������������������������������������������������������������������� 202
Underscore.php (2)����������������������������������������������������������������������������������������������������������������������������� 204

Miscellaneous Libraries����������������������������������������������������������������������������������������������� 206


Saber�������������������������������������������������������������������������������������������������������������������������������������������������� 206
Functional PHP����������������������������������������������������������������������������������������������������������������������������������� 207

Other Libraries�������������������������������������������������������������������������������������������������������������� 211



■Chapter 9: Processing Big Data with Functional PHP��������������������������������������� 213
What Is Big Data?��������������������������������������������������������������������������������������������������������� 213
Introducing Hadoop������������������������������������������������������������������������������������������������������ 214
About MapReduce�������������������������������������������������������������������������������������������������������� 214
Installing Hadoop���������������������������������������������������������������������������������������������������������� 215
Tools��������������������������������������������������������������������������������������������������������������������������������������������������� 215

Creating Hadoop Jobs in PHP��������������������������������������������������������������������������������������� 218


Further Reading���������������������������������������������������������������������������������������������������������������������������������� 227

ix

www.allitebooks.com
■ Contents


■chapter 10: Afterword��������������������������������������������������������������������������������������� 229
Where to Now?������������������������������������������������������������������������������������������������������������� 229
Giving Feedback and Getting Help and Support����������������������������������������������������������� 230

■Appendix A: Installing PHP and Libraries���������������������������������������������������������� 231
Compiling and Installing PHP��������������������������������������������������������������������������������������� 231
Microsoft Windows����������������������������������������������������������������������������������������������������������������������������� 232
macOS/OS X��������������������������������������������������������������������������������������������������������������������������������������� 232
Linux/Unix������������������������������������������������������������������������������������������������������������������������������������������� 233

Compiling and Installing (Extra) Core Extensions��������������������������������������������������������� 234


Installing Multiple Versions of PHP������������������������������������������������������������������������������� 235
Further Reading���������������������������������������������������������������������������������������������������������������������������������� 236
Tools��������������������������������������������������������������������������������������������������������������������������������������������������� 236

PEAR and PECL������������������������������������������������������������������������������������������������������������� 236


Composer��������������������������������������������������������������������������������������������������������������������� 237
Symfony2 Bundles������������������������������������������������������������������������������������������������������� 237
Getting Help������������������������������������������������������������������������������������������������������������������ 237
The PHP Manual��������������������������������������������������������������������������������������������������������������������������������� 237
Official Mailing Lists��������������������������������������������������������������������������������������������������������������������������� 238
Stack Overflow����������������������������������������������������������������������������������������������������������������������������������� 238
Other Books���������������������������������������������������������������������������������������������������������������������������������������� 238
Newsgroups��������������������������������������������������������������������������������������������������������������������������������������� 238
PHP Subredit��������������������������������������������������������������������������������������������������������������������������������������� 239
PHP on GitHub������������������������������������������������������������������������������������������������������������������������������������ 239

File and Data Format Libraries for PHP������������������������������������������������������������������������ 239


Office Documents������������������������������������������������������������������������������������������������������������������������������� 240
Compression, Archiving, and Encryption�������������������������������������������������������������������������������������������� 242
Graphics��������������������������������������������������������������������������������������������������������������������������������������������� 243
Audio�������������������������������������������������������������������������������������������������������������������������������������������������� 244
Multimedia and Video������������������������������������������������������������������������������������������������������������������������� 244

www.allitebooks.com
■ Contents

Programming, Technical, and Data Interchange��������������������������������������������������������������������������������� 245


Miscellaneous������������������������������������������������������������������������������������������������������������������������������������� 246


■Appendix B: Command-Line PHP����������������������������������������������������������������������� 247
PHP Without a Web Server������������������������������������������������������������������������������������������� 247
What’s Different About the CLI SAPI?��������������������������������������������������������������������������� 248
Further Reading���������������������������������������������������������������������������������������������������������������������������������� 249

CLI SAPI Installation����������������������������������������������������������������������������������������������������� 249


PHP Command-Line Options���������������������������������������������������������������������������������������� 250
Further Reading���������������������������������������������������������������������������������������������������������������������������������� 253

Command-Line Arguments for Your Script������������������������������������������������������������������� 253


Different Ways to Call PHP Scripts������������������������������������������������������������������������������� 255
From a File������������������������������������������������������������������������������������������������������������������������������������������ 255
From a String�������������������������������������������������������������������������������������������������������������������������������������� 255
From STDIN����������������������������������������������������������������������������������������������������������������������������������������� 255
As a Self-Executing Script: Unix/Linux����������������������������������������������������������������������������������������������� 256
Further Reading���������������������������������������������������������������������������������������������������������������������������������� 257
As a Self-Executing Script: Windows�������������������������������������������������������������������������������������������������� 258

Windows php-win.exe�������������������������������������������������������������������������������������������������� 258


“Click to Run” Your PHP����������������������������������������������������������������������������������������������� 258
Clickable Icons: Linux������������������������������������������������������������������������������������������������������������������������� 259
Further Reading���������������������������������������������������������������������������������������������������������������������������������� 259
Clickable Icons: Windows������������������������������������������������������������������������������������������������������������������� 259
Clickable Icons: Ubuntu Unity������������������������������������������������������������������������������������������������������������� 260
Further Reading���������������������������������������������������������������������������������������������������������������������������������� 261

Quitting Your Script from Within����������������������������������������������������������������������������������� 261


Further Reading���������������������������������������������������������������������������������������������������������������������������������� 262

Thinking About Security����������������������������������������������������������������������������������������������� 262


Further Reading���������������������������������������������������������������������������������������������������������������������������������� 263

xi
■ Contents

CLI-Specific Code Frameworks������������������������������������������������������������������������������������ 264


Further Reading���������������������������������������������������������������������������������������������������������������������������������� 264

PHP REPLs�������������������������������������������������������������������������������������������������������������������� 265


PsySH������������������������������������������������������������������������������������������������������������������������������������������������� 267
Boris��������������������������������������������������������������������������������������������������������������������������������������������������� 267
phpa���������������������������������������������������������������������������������������������������������������������������������������������������� 267
PHP Interactive����������������������������������������������������������������������������������������������������������������������������������� 268
Sublime-worksheet���������������������������������������������������������������������������������������������������������������������������� 268
phpsh�������������������������������������������������������������������������������������������������������������������������������������������������� 268
iPHP���������������������������������������������������������������������������������������������������������������������������������������������������� 268


■Appendix C: Functional Programming Resources��������������������������������������������� 269
Other Programming Languages����������������������������������������������������������������������������������� 269
Functional Programming and Other Paradigms����������������������������������������������������������� 269
Articles����������������������������������������������������������������������������������������������������������������������������������������������� 269
Online Books��������������������������������������������������������������������������������������������������������������������������������������� 270
Videos������������������������������������������������������������������������������������������������������������������������������������������������� 270

Online Courses������������������������������������������������������������������������������������������������������������� 271


Functional Programming Design Patterns�������������������������������������������������������������������� 272
PHP Functional Basics�������������������������������������������������������������������������������������������������� 272
Data Structures������������������������������������������������������������������������������������������������������������ 273
Mutability in PHP���������������������������������������������������������������������������������������������������������� 273
Map, Filter, Reduce and Other Array Functions������������������������������������������������������������ 273
Recursion and Trampolines������������������������������������������������������������������������������������������ 274
Partial Functions and Currying������������������������������������������������������������������������������������� 274
Functional Composition������������������������������������������������������������������������������������������������ 274
Monads������������������������������������������������������������������������������������������������������������������������� 274
Types���������������������������������������������������������������������������������������������������������������������������� 275
Profiling������������������������������������������������������������������������������������������������������������������������ 276
Memoization����������������������������������������������������������������������������������������������������������������� 277

xii
■ Contents

Lazy Evaluation������������������������������������������������������������������������������������������������������������ 277


Relevant PHP Manual Sections����������������������������������������������������������������������������������������������������������� 277

Parallel Programming��������������������������������������������������������������������������������������������������� 278


Testing�������������������������������������������������������������������������������������������������������������������������� 278
Event-Based Programming������������������������������������������������������������������������������������������ 278
Asynchronous PHP������������������������������������������������������������������������������������������������������� 278
Big Data/Hadoop���������������������������������������������������������������������������������������������������������� 279
General-Purpose Libraries�������������������������������������������������������������������������������������������� 280
Functional Framework������������������������������������������������������������������������������������������������� 286
Lisp in PHP������������������������������������������������������������������������������������������������������������������� 286
Other Miscellaneous Topics������������������������������������������������������������������������������������������ 286
PHP RFCs: The Future��������������������������������������������������������������������������������������������������� 286
The Wikipedia Glossary������������������������������������������������������������������������������������������������ 287

Index��������������������������������������������������������������������������������������������������������������������� 289

xiii
About the Author

Rob Aley I’ve been programming in PHP since late 2000. Initially it
wasn’t by choice because my preferred languages at the time were Perl
and Delphi (also known as Object Pascal). Things began to change after I
graduated from the University of Leeds with a degree in computer science
in 1999 and started out in a career as a freelance web developer. After only
a couple of months I was offered the opportunity to take over a (relatively
speaking) substantial government web site contract from a friend who
was exiting the freelance world for the safer and saner world of full-time
employment. The only catch was that several thousand lines of code had
already been written, and they were written in a relatively new language
called PHP. Oh, and the only other catch was that I had about a week to
learn it before taking over the site. So, as was the way at the time, I popped
down to the local Waterstones bookshop. (For the younger among you
that’s where we used to get books. And we had to go out and get them.
Or order online and wait many days for them to be delivered.) With my
paper copies of The Generic Beginner’s Complete Guide to PHP and MySQL
for Dummies Compendium (I may not have recalled the titles completely
correctly), I settled down with a pint of ale (I’m in Yorkshire at this point, remember) and set about reading
them. A few days later I was coding like a pro (well, stuff was working), and 17 years later I haven’t looked
back. Over those 17 years PHP has changed vastly (the source code for the government web site I mentioned
was littered with comments like “# Would have used a foreach here, if PHP had one…”) and so have I. I like to
think that both I and PHP have only improved and matured over the years.
After a varied career as a freelancer and starting up a couple of, er, startups (IT related and not) with
varying (usually dismal) success, I spent the past ten years as a programmer at the University of Oxford.
My day job involved performing medium-scale data acquisition and management, doing statistical analysis,
and providing user interfaces for researchers and the public. The majority of my development work was
done in PHP, either developing new projects or gluing together other people’s software, systems, and
databases. I’ve recently left the university to concentrate on writing books like this and providing consulting
and training (in PHP, information governance, and related areas). But I’m still programming in PHP!
Throughout my career I’ve always used PHP for web development, but for desktop GUI work I initially
used Delphi (and then Free-Pascal/Lazarus), complemented with Bash shell scripting for CLI-based
tasks. This was mainly because I learned them while at university. However, as PHP has matured, I’ve
increasingly used it beyond the Web, and now I rarely use anything else for any programming or scripting
task I encounter. Having been immersed in other languages such as C++, JavaScript, Fortran, and Lisp
(and probably others that my brain has chosen deliberately not to remember) by necessity during university
and in some of my freelance jobs, I can honestly say that PHP is now my language of choice, rather than of
necessity. At university (in the late 1990s) I took a couple of classes that involved functional programming,
but at the time I really didn’t “get the point.” It’s only in recent years that I’ve picked up functional-style
programming again, partly because of the “buzz” that’s developed around it and partly because as my
programming styles have “matured,” I’ve seen the advantages to functional coding.

xv
■ About the Author

When I’m not tied to a computer, I would like to say I have lots of varied and interesting hobbies. I used
to have. I could write a whole book (which wouldn’t sell well) about where I’ve been and what I’ve done,
and I’d like to think it’s made me a well-rounded person. But these days I don’t have any. In large part, this
is because of the demands of my three gorgeous young daughters, Ellie, Izzy, and Indy; my gorgeous wife,
Parv; and my even more gorgeous cat, Mia. And I wouldn’t have it any other way. That’s what I tell myself,
anyway….
—Rob Aley

xvi
About the Technical Reviewer

Christopher Pitt is a developer and writer, working at SilverStripe. He usually works on application
architecture, though sometimes you’ll find him building compilers or robots. He is also the author of several
web development books and is a contributor on various open source projects like AdonisJs.

xvii
Acknowledgments

Isaac Newton said, “If I have seen further, it is by standing on the shoulders of giants.” This book builds on,
and I hope adds to, the work of many others, the most notable of whom I would like to acknowledge here.
• The authors of, and contributors to, the official PHP Manual: This is an invaluable
reference for PHP functions and syntax, to which I referred frequently during writing
this book, both for fact checking and as an aide-mémoir. Thanks!
• The collective PHP and functional programming wisdom of the Internet: For more
than 17 years I’ve used you for learning, research, play, and profit. There are too
many sites and too many people to list here; if you’ve written about PHP on the Web,
then you may well be one of them. Thanks!
• My family: Thanks for allowing me a modicum of time to write this book and
supporting me unconditionally in everything I do. Usually. If I ask first. And there’s
not something more important going on. And usually with conditions. Thanks!

xix
PART I

Functional Programming
in PHP 7
CHAPTER 1

Introduction

Functional programming isn’t something that is often associated with PHP. Yet for quite a while PHP has had
all the features necessary to create software using the functional paradigm. In this book, you’ll take a look
at what functional programming is, how to do it in PHP, and the different ways in which you can use it to
improve your PHP software.

Who Is This Book For?


This book isn’t an introduction to PHP itself; it assumes you have some basic (or, indeed, advanced)
experience in PHP scripting. You don’t need to be an expert to follow along; I’ll cover all the key concepts
in PHP you’ll need to know to be able to implement functional designs in your code and point you in the
direction of resources such as web sites and other books that you can use to learn or investigate any related
concepts that I don’t cover directly.
Absolute PHP beginners aside, this book is suitable for all programmers. Whether you have a pressing
need to learn functional programming (perhaps you’ve taken over a functional PHP code base) or you are
just interested in finding out what the “buzz” around functional programming is all about, there is something
in this book for you. There’s even likely to be something for those skeptical about creating software using the
functional programming paradigm. I think that most programmers will find useful lessons and code patterns
to take away from the functional programming style that will enhance their object-oriented or procedural
programming work. If all else fails, knowledge of functional programming looks good on your résumé!

What Is Functional Programming?


Functional programming is a declarative programming paradigm that abstracts code into
pure, immutable, side-effect-free functions, allowing the programmer to compose such
functions together to make programs that are easy to reason about.

That is my definition of functional programming. Ask five other functional programmers to define functional
programming and you’ll get four more answers (two just copied the same answer from Wikipedia). There’s
no “standard” definition; different people and different programming languages implement functional
programming elements differently. These differences are partly because of the practicalities of the language
in question and sometimes because of the target platforms, data, and usage scenarios, but often they come
down to what I call “programming religion”: a fixed, sometimes irrational, but often deeply held belief of
how a particular paradigm should be. Even within the small community of PHP functional programmers,
you won’t find an exact consensus. In PHP, functional programming is not a core concept, but even in
languages where it is (e.g., Lisp, Scala, etc.), there are many “related” understandings of what constitutes true
functional programming. While that may sound problematic, you’ll still “know it when you see it,” and when
it gets woolly around the edges, you can choose to define it in any way you see fit!
© Rob Aley 2017 3
R. Aley, Pro Functional PHP Programming, DOI 10.1007/978-1-4842-2958-3_1
Chapter 1 ■ Introduction

PHP isn’t a pure functional programming language, but you can still use it for functional programming
(which is good; otherwise this book wouldn’t be very long). A few elements of what some purists consider to
be essential functional programming concepts are harder to implement with PHP’s standard syntax, so it’s
perhaps slightly more accurate to say that you can program in a functional programming “style” in PHP.
Let’s now look a little more in depth at what functional programming actually is in practice. Functional
programming is a “declarative” style of programming, which means you specify what you want it to do rather
than how you want to do it. It’s a higher level of abstraction than you may be used to with OO or procedural
programming. However, you almost certainly use declarative programming on a day-to-day basis when using
SQL, HTML, regular expressions, and similar languages. Consider the SQL snippet shown in Listing 1-1.

Listing 1-1. declarative.sql


SELECT forename,

       Surname

FROM   users

WHERE  username = 'rob'

       AND password = 'password1';

This is telling your database server what you want it to do (select the real name based on super-secret
security credentials), but you don’t tell it how to do it. You don’t tell it the following:
• Where to look on disk for the data
• How to parse or search the data for matching records
• How to determine whether a record matches your criteria
• How to extract the relevant fields from the record
And so on. You simply tell it what you want it to achieve for you.
Now obviously, at some point, you need to tell the computer how to do something. With the SQL example
in Listing 1-1, you do that by getting some rather clever people to write database management software
(DBMS) for you. In functional programming, you’ll tend to need to write the implementation code yourself,
but to make it a manageable task, you break that down into the smallest possible chunks and then use a
hierarchical chain of declarative function calls to tell the computer what to do with that code. If you use the
Composer dependency management system, you will already be using a similar paradigm: there are many
libraries of code available that abstract away the tasks that you need to do; you simply “compose” a list of
libraries together to do what you want. In functional programming, you do exactly the same; you take functions
that do something (like the libraries Composer provides) and compose them together into a program.
Having a program that is essentially a list of what you want to achieve sounds very good on paper,
and indeed it makes it easy to understand and reason about your program. To make the idea a little more
concrete, let’s take a look at a small functional-style program (Listing 1-2).

Listing 1-2. example.php


<?php

require_once('image_functions.php');

require_once('stats_functions.php');

4
Chapter 1 ■ Introduction

require_once('data_functions.php');

$csv_data = file_get_contents('my_data.csv');

$chart = make_chart_image (

                                 generate_stats (

                                         data_to_array (

                                                 $csv_data

                                                 )

                                         )

                                 );

file_put_contents('my_chart.png', $chart);

This is clearly some code that has been abstracted into a set of functions that set out what it does (draw
a chart based on some stats prepared from some data that is read in). You can also probably see that the
how is hidden away in the required files at the top, but it is still clear as to what the program does. Should
your requirements change and instead of drawing a chart you want to print a table, you can simply swap
out draw_chart() for print_table() and it is clear what will happen. This is a (very loose) example of a
functional program.
That all sounds great. But without even considering the code hidden away in the required files, your
programmer instincts are probably telling you that chaining random functions together, and swapping out
one for another, is a risky proposition particularly when you can’t see how they’re implemented. For instance,
how do you know that read_data() will return data in the correct format for prepare_stats() to work on?
And how can you be sure that you can swap out draw_chart() for prepare_stats() and it will all still work
as you expect? Clearly, functional programming involves a little more than “chuck it all in a function with a
descriptive name,” and as you go through the book, you’ll look at the various ways to structure functions so
that you can use them as “little black boxes” of code that can be easily and reliably strung together.
Functional programming revolves around functions, as the name implies. However, functions in the
functional programming sense aren’t quite the same as functions in the PHP syntax sense, although you will
use PHP’s implementation of functions to implement FP functions. A functional programming function is
often referred to as a pure function and has several important characteristics that can be mimicked with, but
aren’t enforced by, PHP’s syntax. A pure function has the following traits:
• Is referentially transparent
• Is devoid of side effects
• Has no external dependencies
I’ll talk more in detail about what these features mean in the next couple of chapters, but they boil down
to a function being a small self-contained “black box” that takes well-defined inputs, produces well-defined
outputs, and given the same inputs always produces the same outputs. In particular, the function only
acts on the inputs it is given (it doesn’t take into account any external state or data and relies only on the
parameters it is called with), and the only effect it has is to return some output (which will be the same each
time you give it the same input); thus, it doesn’t alter the state of the program or system outside of itself.

5
Chapter 1 ■ Introduction

In the example program in Listing 1-2, if you give exactly the same CSV file to read_data() each time,
and assuming you have properly used functional programming, you can be sure that draw_chart() will
produce exactly the same chart each time, regardless of anything else going on elsewhere in the program or
on your system. This ability to be sure of, and reason about, the program flow leads to a number of benefits
for the functional programming paradigm that you’ll discover as you learn more about implementing
functional programming programs.

Functional Programming Is SOLID


If you come from an object-oriented programming background, you are probably familiar with the SOLID
principles for composing OO code. Although written for OOP, the SOLID principles actually embody
the principles of functional programming very well; indeed, some are inherent in the way functional
programming is defined. Understanding these principles will help you to understand some of the key traits
of functional programming. If you’re not familiar with SOLID, it is an acronym with each letter standing for
one of the five basic principles of good OO design. I’ll cover each in turn.

S: Single Responsibility Principle (SRP)


Each function is responsible for only one task. “Do one thing, and do it well.” In functional programming,
you break your program down into single-task functions. When any other function needs to do that task,
they call that function. And when that task changes in specification, only that function has to be changed.

O: Open/Closed Principle (OCP)


Functions should be “open for extension but closed for modification.” In functional programming, this
means that when you need to extend the behavior of a function, you don’t modify the existing function but
compose it with (or call it from) other functions that create the new extended functionality.

L: Liskov Substitution Principle (LSP)


In OOP, this principle deals with the ability to substitute an object with an instance of a subtype of that
object. In functional programming, that most precisely maps onto a concept called contravariance in
functors, something that is more advanced (and also more theoretical and less practical) than you will
learn in this book. However, there is a similar related principle that you will look at, that of referential
transparency. This basically means that regardless of what else is happening in your program, a given
function (with a given input) can be substituted with the value it returns in the program, and the program
will continue to operate as expected.

I: Interface Segregation Principle (ISP)


This principle means that the parameters required for calling a function should only be those needed for
the task you are carrying out. Interfaces to functions should be split down as specifically as possible, rather
than providing general interfaces that contain parameters not relevant to the intent of the calling client code.
Functional programming achieves this almost by default when chopped down into single responsibility
functions because of the structured interface needed for efficient composition.

6
Chapter 1 ■ Introduction

D: Dependency Inversion Principle (DIP)


This principle states the following:
• High-level modules should not depend on low-level modules. Both should depend
on abstractions.
• Abstractions should not depend on details. Details should depend on abstractions.
This is more or less the definition of declarative programming. Your low-level functions that have the
implementation details form an abstraction on which your higher-level “declarative” functions can operate.
Don’t worry if all of these principles and terms don’t make sense right now; just keep them in mind
(or refer to them as needed) as you go through the book, and by the end you should be able to see how the
SOLID principles apply naturally to the functional programming paradigm.

Further Reading
• The SOLID principles on Wikipedia
• https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)

What Are the Benefits of Functional Programming?


I’ve touched on some of the benefits. But in case it isn’t already clear, these are the key benefits that most
programmers will gain from using functional programming techniques:
• You will create code that is easy to reason about. This means that it is less error
prone, easier to update, and easier to understand the flow of the code.
• You will create code that is easier to test. This is a side effect of some of the properties
of the functional programming paradigm, such as immutability, referential
transparency, and lack of external dependencies.
• You can create higher-performance code, using techniques such as lazy evaluation,
parallelization, and caching.

Who Uses Functional Programming, and Why?


I first learned functional programming some 20-odd years ago at university when I studied for my computer
science degree. I really didn’t see the point of it at the time and got quite a poor grade in that class because
of my lack of interest in learning it, as I couldn’t get my head around why anyone would want to use it “in
real life.” At the time, outside of academia and certain highly specialized domains such as engineering and
finance, it wasn’t in widespread use. However, over the years that has changed, and now many more people
than you may think use functional programming, for many varied reasons.
It’s prominent in many areas of mainstream IT these days, not just in specialized industries, academia,
and startups run by “Silicon Valley hipsters”! Large companies such as Netflix, LinkedIn, and Twitter use
functional programming to deliver robust services at scale. Some people use it because it is easy to reason
about. Some use it because its lack of “side effects” makes it easy to parallelize and scale. Some use it
because it maps neatly to mathematical constructs used in various fields of endeavor such as engineering,
data science, and finance. It is being used in some industries because its declarative nature allows the
creation of domain-specific languages (DSLs). DSLs can allow less skilled users to create or understand
programs, allow easier mapping of business requirements and processes into software, and improve
programmer productivity by providing task-specific abstractions.

7
Chapter 1 ■ Introduction

Functional programming has been gaining more and more traction over the past few years. Modern
functional languages like Racket, Clojure, and F# are building steam, and even PHP is getting in on the act
with an ever-growing range of functional programming libraries becoming available on GitHub and through
Composer.
But while it’s currently a hot topic in modern computing, functional programming’s history in
computing stretches back to Lisp in the 1950s, while lambda calculus (the mathematical abstraction on
which functional programming is based) and the more abstract field of combinatory logic began life in the
1920s and 1930s. Both directly in languages like Lisp and Scheme and indirectly in functional-style code
written in most programming languages, functional programming has had an influence in many fields of
computing over the years. Many companies write functional programming code and rely on functional
programming software on a day-to-day basis (whether they realize it or not!).

Is Functional Programming “All or Nothing”?


When people start learning functional programming, they often start asking if they need to tear up their
old OOP code and start from scratch. My answer is no (although the purists would say yes). Functional
programming can happily live alongside OOP or procedural code, or indeed any other programming
paradigm, as long as you understand where your functional programming code starts and stops. Because
of the nature of functional programming, it is often easier to put functional programming structures inside
objects or traditional functions/procedural code blocks, rather than the other way around.
Particular sections of code that can benefit from functional programming (such as business logic
processes and high-performance algorithms) can often be good starting places for introducing functional
programming into your code base. Because functional programming isn’t a core feature of PHP, it actually
makes it easier to mix and match paradigms as you see fit. In other traditional functional programming
languages, things are more restrictive; for instance, Haskell doesn’t have any OO capabilities, whereas F# is
written around a specific FP-OO hybrid paradigm. Functional programming has many things in common
with OOP; indeed, a closure (a function packaged with associated program state) is somewhat comparable
to a streamlined object, and program flow control in many OO programming patterns somewhat mimics
the functional programming style of flow. PHP is, as usual, flexible and says “do what you want,” which can
be both a blessing or (if you don’t do it right) a curse. That’s a common complaint about PHP in general,
though, and is simply solved by always programming correctly!
If you’re interested in learning the differences between the different programming paradigms that
people have come up with over the years, then Wikipedia has got you covered with a fairly comprehensive
comparison of the main features of each. Note that PHP is a “Turing complete” language, which basically
means that if something can be computed, then PHP can compute it. This also means that any of the
paradigms described can be implemented in PHP (whether you’d want to is another matter, although I think
that most offer at least something that a good programmer can add to their mental toolbox for use at the
appropriate time). If this book whets your appetite for doing things a little differently, then maybe check out
the Wikipedia list for some more ways of mixing up your code.

Further Reading
• A comparison of programming paradigms on Wikipedia
• https://en.wikipedia.org/wiki/Comparison_of_programming_paradigms

8
Chapter 1 ■ Introduction

Why Use PHP for Functional Programming?


Just about everyone who has heard the title of this book has said to me, “You don’t use PHP for functional
programming” (besides my wife, who said, “That sounds super-boring”). Well, they’re all wrong (including
my wife). There’s absolutely no reason not to use PHP (well, aside from the reasons listed in the “Why Not to
Use PHP for Functional Programming” section). And it’s not super-boring.
In all seriousness, PHP has just about everything you need to write good functional programming
code. It has first-class support for functions, it has libraries that help abstract boilerplate code, and there
is a growing body of documentation and help available (including the very book you’re reading now). But
most of all, you already know PHP. You’re learning a new programming paradigm, so why burden yourself
with getting to grips with a new language at the same time? Indeed, if you get to know the paradigm first in
an environment you’re already comfortable with, you will likely find it easier to pick up more specialized
functional programming languages like Haskell later, where the language features implicitly rely on you
being familiar with the functional programming paradigm.
Perhaps if you were not familiar with programming at all and wanted to learn functional programming,
starting with something like Haskell may be fine. But you’re coming with the baggage of familiarity of OO
or procedural programming, and a pure functional programming language will feel alien to you until you’re
comfortable with functional programming as a concept. You’ll waste a lot of time trying to work out how
to implement features and constructs that just don’t exist in the functional programming world, instead of
getting on and writing code.

Why Not to Use PHP for Functional Programming


There are one or two cases where using PHP in this way might not be a good idea (just don’t tell anyone I
said so).
• You have a particular business case/requirement to only use functional programming.
In PHP there is nothing to stop you from mixing your programming paradigms, and
sometimes it is tempting (or pragmatic) to do so. So if you need to ensure you stick to
functional programming code alone, then it’s probably best not to use PHP.
• You need top-notch, first-rate commercial support. As noted earlier, there is growing,
good-quality support for functional programming in the PHP community. But
“traditional” functional programming languages have more, particularly in the area
of paid commercial support.
• You think that PHP is dying, has serious issues, or isn’t a real programming language.
Some people still hold these views, even as PHP goes from strength to strength.
Nevertheless, if the mention of PHP sends prickles up your spine, implementing
your programs in functional programming within PHP won’t magically make that
feeling go away. As you’re reading this book, it’s more likely that you don’t feel like
that, but others around you (your boss or colleagues?) may, and as wonderful as this
book is, it’s unlikely to sway their opinion of PHP itself. You’ll likely need to do what’s
pragmatic in that situation—quit and start your own company like I did.
• Your colleagues don't know functional programming, so your code may be harder for
them to maintain. This is simple to solve: buy them a copy of this book!

9
Chapter 1 ■ Introduction

PHP Versions
At the time of writing, the current stable release of PHP is 7.1.2, and it would be lovely if that was the version
that everyone is running. However, it isn’t; indeed, PHP versions all the way back to 5.2 can be found in
mainstream use across hosting providers and inside companies. Tales of people using even older versions
abound in the darker corners of the Internet, and with security updates available only for 5.6 and higher,
such tales are the stuff nightmares are made of. So, which version should you choose (if indeed you have the
choice) for functional programming?
All the code in this book was developed and tested on the current release of version 7.1 of PHP. However,
most of the code will run with minor changes on any version from 5.4 onward. Versions older than 5.4 lack
the language support for anonymous functions and closures, which means that functional programming
isn’t practical. I’ll point out any differences between version support throughout the book, the most notable
of which will be the lack of support for type declarations (also known as type hints) for scalar variables in the
series 5 versions. Do note that “Active Support” for the last 5.x version, 5.6, has now ended, and “Security Fixes
Only” support is due to be withdrawn in late 2018, so using a 7.x version is highly recommended if possible.
As well as continued support from the PHP maintainers, you’ll find that the lower resource requirements of
PHP 7 will help in some areas of functional programming with PHP such as recursion. That said, you can do
functional programming in PHP 5, and the inevitable upgrade lag in many workplaces may mean that you
have no choice to use a 5.x version, so I’ll do my best to cover the differences as I go along.

Conclusion
In this chapter, you started looking at what functional programming is and why it can be useful in your PHP
development. Functional programming can be hard to grasp from such an abstract discussion, so don’t
worry if you don’t “get it” yet. As you go through the next few chapters, you’ll get a better feel for it as you see
the programming concepts behind it and examples of functional code.

10
CHAPTER 2

Functional Programming:
Key Concepts

In this chapter, you’ll look at the key concepts, building blocks, and vocabulary that you’ll need to understand
before getting started on some actual functional programming. Although you are already likely to be using
functions and closures in your everyday programming, it’s worth taking the time to read the following sections
that describe them from first principles as some of the details that you take for granted when using them
in object-oriented or plain procedural programming can trip you up when applying them in the functional
paradigm. As functional programming is rooted in math, you’ll also take a look some language that you may
be unfamiliar with and see it in terms that are easy to understand for a regular programmer.
The concepts presented in this chapter, taken individually, may paint a confusing picture about what
functional programming is and what benefits it can bring. For instance, I’ll talk about immutability, which is
essentially the inability to change a value. That seems like a drawback at first rather than a benefit, but when
you draw all of these concepts together over the next couple of chapters, you will see that immutability plays
a key part in the flexible recipe-like nature of functional programming and is one of the factors that allows
you to easily reason about your functional code.
So, for now, try to focus on understanding the individual concepts as presented and don’t worry too
much about how they all fit together. Learning functional programming is much like writing functional
programming code—lots of small independent functions/ideas composed into an over-arching scheme that
eventually does something!

Examining State
As you go through the book, particularly when you look at types, there may be times when you do not feel
confident about the state of a variable, object, or function in your code. State includes the current contents
of the thing you are examining and its current type. PHP provides a couple of handy functions, print_r and
var_dump, to help you “look” at what’s happening in your code. See Listing 2-1.

Listing 2-1. examine.php


<?php

define('MY_CONSTANT', 'banana');

$my_function = function ($data) {


       return $data;
};

© Rob Aley 2017 11


R. Aley, Pro Functional PHP Programming, DOI 10.1007/978-1-4842-2958-3_2
Chapter 2 ■ Functional Programming: Key Concepts

$my_array = [1,2,'apple',MY_CONSTANT,$my_function];

echo "print_r output :\n\n";

print_r($my_array);

echo "\n\n var_dump output :\n\n";

var_dump($my_array);

Running the script in Listing 2-1 gives the output shown in Listing 2-2.

Listing 2-2. examine-output.txt


print_r output :

Array
(
    [0] => 1
    [1] => 2
    [2] => apple
    [3] => banana
    [4] => Closure Object
        (
            [parameter] => Array
                (
                    [$data] => <required>
                )

        )

var_dump output :

array(5) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  string(5) "apple"
  [3]=>
  string(6) "banana"
  [4]=>
  object(Closure)#1 (1) {
    ["parameter"]=>
    array(1) {
      ["$data"]=>
      string(10) "<required>"
    }
  }
}
12
Chapter 2 ■ Functional Programming: Key Concepts

As you can see, the functions produce similar output. print_r is formatted for easier reading by humans,
and var_dump provides slightly more information about basic types. I usually use var_dump, reverting to
print_r when I have a particularly dense data structure to look through as the formatting can make it easier.
Another function that’s particularly useful in functional programming is debug_print_backtrace().
Functional programming usually involves composing many single-purpose functions together into stacks
of functions that represent your program. When an error does occur, it can be hard to track down exactly
which of the many functions you have used in your stack is causing the error. A backtrace shows where you
are in the function call stack at that moment and is commonly displayed by debuggers and code profilers.
The debug_print_backtrace() function can allow you to print the call stack from within your code, as the
contrived example in Listing 2-3 demonstrates (Listing 2-4 shows the output).

Listing 2-3. backtrace.php


<?php

function prepare_text($text) {

    return make_headline($text);

function make_headline($text) {

    return add_h_tags( upper_case($text) );

function upper_case($text) {

    return strtoupper($text);

function add_h_tags($text) {

    debug_print_backtrace();

    return '<h1>'.$text.'</h1>';

$title = prepare_text('testing');

echo $title;

Listing 2-4. backtrace-output.txt


#0  add_h_tags(TESTING) called at [backtrace.php:12]
#1  make_headline(testing) called at [backtrace.php:6]
#2  prepare_text(testing) called at [backtrace.php:30]
<h1>TESTING</h1>

13
Chapter 2 ■ Functional Programming: Key Concepts

The top of the list has the most recent function called (in this case, add_h_tags()), all the way down to
the initiating function (prepare_text()). Note that although the make_headline() function calls the upper_
case() function, it is not in the backtrace. This is because it has completed its execution and is not waiting
for the output of the next function in the chain before it returns its own output (as is the case for the other
three functions, which are still in the stack).
The three functions mentioned are most useful when you’re learning and experimenting with code,
particularly if you use a read-eval-print-loop (REPL; see Appendix B for more information) to test and hack
on code. In proper development and production code, you should use debuggers, profilers, and secure
logging to keep track of what your code is doing; using print_r and var_dump can accidentally spill internal
data to the outside world and cause various security issues.

Mutability and Immutability


If something is mutable, it means you can change it. Variables are mutable. Consider the code in Listing 2-5
and Listing 2-6.

Listing 2-5. mutable.php


<?php
$a = 1;

var_dump($a);

$a = 2;

var_dump($a);

$a = "Banana";

var_dump($a);

Listing 2-6. mutable-output.txt


int(1)
int(2)
string(6) "Banana"

First, $a is set to 1. Then, because it is mutable, you can “mutate” (change) it to be equal to 2. Finally,
you mutate it again to Banana. Note that in the last change, you not only mutate the variable but also the
type, from int to string.
In functional programming, you want values (represented by functions) to be immutable. This is
important in helping you to reason about your program and to allow you to loosely couple functions
together. You’ll look at this more in detail later.
PHP has limited support for immutability, mainly in the form of “constants” defined using either the
define() function or the const keyword. There are a few differences between how and what you can declare
constant when using define() versus const, but once declared, the constants created by either method are
the same. One thing they both have in common is that only scalars or arrays can be constants. Listing 2-7
tries to create a constant from a variable holding an anonymous function. Listing 2-8 shows the output.

14

www.allitebooks.com
Chapter 2 ■ Functional Programming: Key Concepts

Listing 2-7. constant-func.php


<?php

$double = function ($input) {


    return $input * 2;
};

define('DOUBLE',$double);

echo "Double 2 is " . $double(2) . "\n";

echo "Double 2 is " . DOUBLE(2) . "\n";

Listing 2-8. constant-func-output.txt


PHP Warning:  Constants may only evaluate to scalar values or arrays in constant-func.php on
line 8
Double 2 is 4
PHP Fatal error:  Uncaught Error: Call to undefined function DOUBLE() in constant-func.
php:12
Stack trace:
#0 {main}
  thrown in constant-func.php on line 12

Here you can see that you get a warning when trying to use the variable holding the function in
define(), and when you try to use the DOUBLE constant, you get confirmation (via a fatal error) that it did
indeed fail to be defined.
So, without much help from PHP, you will need to ensure immutability yourself through discipline
when coding. One of the key ways to help achieve this is to avoid using assignment, and you’ll look at
ways to do this as you go through the book. The lack of support for immutability in PHP (compared to
other languages) is one of the main things people will point out when you tell them you are using PHP for
functional programming. However, it does not in any way stop you from writing functional programs in PHP;
you simply need to keep it in mind as you code.
As well as watching what you do yourself, you need to keep half an eye on what PHP is doing. A key
thing to think about is how PHP’s own functions operate on your variables. For instance, the function sort()
mutates (i.e., sorts) the array it is passed, rather than returning a new array that is a sorted version of the old
array (and leaving the old array unmutated). However, you can make your own immutable version of sort()
quite easily (see Listing 2-9 and Listing 2-10).

Listing 2-9. sort.php


<?php

function immutable_sort($array) {

    sort($array);

    return $array;

15
Chapter 2 ■ Functional Programming: Key Concepts

$vegetables = ['Carrot', 'Beetroot', 'Asparagus'];

# Sort using our immutable function

$ordered = immutable_sort( $vegetables );

print_r( $ordered );

# Check that $vegetables remains unmutated

print_r( $vegetables );

# Do it the mutable way

sort( $vegetables );

# And see that the original array is mutated

print_r( $vegetables );

Listing 2-10. sort-output.txt


Array
(
    [0] => Asparagus
    [1] => Beetroot
    [2] => Carrot
)
Array
(
    [0] => Carrot
    [1] => Beetroot
    [2] => Asparagus
)
Array
(
    [0] => Asparagus
    [1] => Beetroot
    [2] => Carrot
)

This works because by default PHP function parameters are passed by value and not by reference. This
means that when you call a function, it gets a copy of any variables that you give as parameters, rather than a
reference to the variable itself. Anything the function does to that copy does not affect the original variable.
PHP does allow you to pass in a parameter by reference (which is what sort() uses to mutate the original
array), but this is not the default. When you pass in an object or resource, you are passing in an object or
resource variable, which is a pointer to that object or resource. The variable is still passed by value; however,
the new copy of the variable is still pointing to the original object or resource, so it acts in a similar manner to
passing by value. You’ll look at that issue in depth in Chapter 7.

16
Chapter 2 ■ Functional Programming: Key Concepts

In most cases, it is obvious which functions will mutate their parameters; they usually don’t supply their
output as a return value, but some take a mixture of by value and by reference parameters, so always check
the PHP Manual if you’re not sure.

Further Reading
• Constants in the PHP Manual
• http://php.net/manual/en/language.constants.php
• A comprehensive synopsis of the differences between define() and const
• http://stackoverflow.com/a/3193704

What Is a Function?
You probably have a reasonable idea about what a function is, and you probably use them regularly in your
PHP code. However, I’ll cover functions from scratch because a good understanding of the fundamentals of
how PHP implements functions, and the different ways of handling them, is necessary to understand how to
implement functional programming in PHP.
You’ll develop a better feeling for exactly what a function is, in terms of functional programming, over
the course of this chapter. But here’s a good starting definition:

A function is a set of instructions, encapsulated into a self-contained, reusable block of code.

PHP lets you work with several different invocations of functions, which you’ll look at in turn next.

Named Functions
A standard named function is the basic way to use functions in PHP. A named function looks something like
the my_function() function in Listing 2-11 (the output is shown in Listing 2-12).

Listing 2-11. named_function.php


<?php

function my_function ( $parameter_1, $parameter_2) {

        $sum =  $parameter_1 + $parameter_2;

        return $sum;

$value1 = my_function(10,20);

var_dump( $value1 );

$value2 = my_function(6,9)

var_dump( $value2 );
17
Chapter 2 ■ Functional Programming: Key Concepts

Listing 2-12. named_function-output.txt


int(30)
int(15)

The function is created using the “function” language construct. It has a name (my_function), which is
used to call it later. It has parameters (in this case two), which allow you to pass values to the code inside the
function. It carries out some useful work (in this case adding the parameters together and returning them).
It has a return statement that sets the value of the function. As you can see from this example, the function’s
value is often dependent on external values, in this case by changing the parameters given as input. The
return value, however, can depend on external sources of state not directly passed in by parameters, as
demonstrated by Listing 2-13 and Listing 2-14.

Listing 2-13. returns.php


<?php

$oranges = 3;

function count_fruit($apples, $bananas) {

    global $oranges;

    $num_fruit = $apples + $bananas + $oranges;

    return $num_fruit;

function get_date() {

    return trim ( shell_exec('date') );

var_dump( count_fruit(6,7) );

var_dump( get_date() );

Listing 2-14. returns-output.txt


int(16)
string(28) "Tue 21 Feb 13:12:37 GMT 2017"

count_fruit() uses the global variable $orange, the value of which is set outside of the function, in its
calculation of the return value. get_date() doesn’t ask for any parameters at all and calculates its return value
based on an external shell command. In both cases, these are potential causes of “side effects,” which you will
look at later, and show that functions in PHP aren’t restricted to operating on only the parameters supplied.

This is a key difference with mathematical functions. The functional in functional programming refers to the
mathematical concept of a function and not the programming concept of a function. Mathematical functions are
pure functions, which you’ll look at shortly.

18
Chapter 2 ■ Functional Programming: Key Concepts

The following are the primary limitations with named functions:


• They cannot be destroyed.
• Their functionality (the code in the function) cannot be changed once defined.
• They are harder to “pass around” because they cannot be assigned to a variable.
• Only the name of the function can be assigned to a variable, rather than the function
itself.
There are limited options for “dynamically” handling named functions, although the call_user_func()
function does offer one way to work in such a manner, as shown in Listing 2-15 and Listing 2-16.

Listing 2-15. userfunc.php


<?php

function list_fruit($item) {

    return ['apple','orange','mango'][$item];

function list_meat($item) {

    return ['pork','beef','human'][$item];

$the_list = 'list_fruit';

var_dump( call_user_func($the_list, 2) );

$the_list = 'list_meat';

var_dump( call_user_func($the_list, 1) );

Listing 2-16. userfunc-output.txt


string(5) "mango"
string(4) "beef"

As you can see, you can pass call_user_func() the name (as a string) of a function (plus any
parameters you want to supply the function), and call_user_func() will return the return value from the
function you called as its own return value. And as you can see, you can change the name of the function in
$the_list (as it is a string variable) and run call_user_func() again, this time running a different function.
This allows you a little dynamism but is quite limited. A similar method is called a variable function, which
you’ll look at in the next section. Since PHP 7.0, you can also use the fromCallable static method of PHP’s
closure object to wrap a named function into something called a closure, which you’ll look at later.
The scope of named functions is also unintuitive. As you’ll see in the section “Scope” later in this chapter,
when you create a variable within a function, by default it isn’t available to code outside of that function. However,
when a named function is instantiated within another function, it is created in the global scope, such that it can
be called from anywhere, and thus it also needs to have a globally unique name. Consider the demonstration in
Listing 2-17 of nested functions, which return a string to illustrate their nesting (Listing 2-18 shows the output).

19
Chapter 2 ■ Functional Programming: Key Concepts

Listing 2-17. name-scope.php


<?php

function a() {

    function b() {

        return "a -> b";

    }

    return "a";

function c() {

    function d() {

        function e() {

            return "c -> d -> e";

        }

        return "c -> d";

    }

    return "c";

var_dump( a() );

var_dump( b() );

var_dump( c() );

var_dump( d() );

var_dump( e() );

Listing 2-18. name-scope-output.txt


string(1) "a"
string(6) "a -> b"
string(1) "c"
string(6) "c -> d"
string(11) "c -> d -> e"

20
Chapter 2 ■ Functional Programming: Key Concepts

Note that you are defining the functions b(), d(), and e() within the scope of other functions, but when
you call them with var_dump, you are calling them from outside their “parent” functions. You can alter this
script to show another property of named functions; they are not created until the scope within which they
are defined is created. In Listing 2-19, you swap the order in which you call c() and d() in the var_dump()
section (with the output shown in Listing 2-20).

Listing 2-19. name-scope2.php


<?php

function a() {

    function b() {

        return "a -> b";

    }

    return "a";

function c() {

    function d() {

        function e() {

            return "c -> d -> e";

        }

        return "c -> d";

    }

    return "c";

var_dump( a() );

var_dump( b() );

var_dump( d() );

var_dump( c() );

var_dump( e() );

21
Chapter 2 ■ Functional Programming: Key Concepts

Listing 2-20. name-scope2-output.txt


string(1) "a"
string(6) "a -> b"
PHP Fatal error:  Uncaught Error: Call to undefined function d() in name-scope2.php:38
Stack trace:
#0 {main}
  thrown in name-scope2.php on line 38

Because you haven’t yet called c(), d() doesn’t exist, and so you get a fatal error. b() could be accessed
fine, as you had already called a(), even though you were in the main program scope when you called it. As
a final demonstration of the problems of named functions, let’s look at the need for a globally unique name.
With a normal variable, you can use the same variable name for different variables, as long as they are in a
different scope (e.g., in different functions). With a named function, that won’t work, as you can see from
Listing 2-21 and Listing 2-22.

Listing 2-21. name-scope3.php


<?php

function f() {

    function g() {

        return "1st g()";

    };

    return "f()";

function h() {

    function g() {

        return "2nd g()";

    };

    return "h()";

var_dump( f() );

var_dump( g() );

var_dump( h() );

22
Chapter 2 ■ Functional Programming: Key Concepts

Listing 2-22. name-scope3-output.txt


string(3) "f()"
string(7) "1st g()"
PHP Fatal error:  Cannot redeclare g() (previously declared in name-scope3.php:7) in name-
scope3.php on line 17

As you can see, you’ve defined g() twice, once inside f() and once inside h(). Despite this, things run
smoothly at first when you call f() and g(), but as soon as you try to call h(), the second instance of g() tries
to declare itself, leading to a fatal error.
Using unique names for functions doesn’t seem like too much of a terrible restriction, until you
consider that if you start including external code libraries with include() or require() or via an autoloader,
those become part of the scope in which your function name must be unique, and it’s harder to ensure that
other people won’t tread on your functional toes! PHP does allow you to “namespace” functions, which
mitigates this issue somewhat; however, that can be considered a somewhat inelegant solution (depending
on who you talk to).

Variable Functions
PHP supports the concept of “variable” functions. This is a dynamic way of calling named functions with a
slightly more succinct syntax than the call_user_func() example you looked at in the previous section. In
essence, if you put parentheses (round brackets) at the end of a variable, PHP will call the named function
stored in the value of that variable (with any parameters you put in the parentheses). See Listing 2-23 and
Listing 2-24.

Listing 2-23. variable.php


<?php

function vehicles( $index ) {

    $types = ["car", "motorbike", "tractor"];

    return $types[$index];

function animals( $index ) {

    $types = ["cow", "pig", "chicken", "horse"];

    return $types[$index];

$get_thing = 'animals'; # string with the name of a function

var_dump( $get_thing(2) ); # add ($index) to call it

$get_thing = 'vehicles'; # change the function

var_dump( $get_thing(2) ); #same "code", different function


23
Chapter 2 ■ Functional Programming: Key Concepts

# Just to show that $get_thing is just a


# standard string, and nothing special...

$get_thing = strrev('selcihev'); # do string things

var_dump( $get_thing ); # it's a string

var_dump( $get_thing(2) ); # call it

var_dump( $get_thing ); # afterwards, still just a string

unset( $get_thing ); # we can destroy it, because it's a string

var_dump( $get_thing );

var_dump( vehicles(2) ); # But the function still exists

# However, it needs to be set to a function that exists

$get_thing = 'people';

var_dump( $get_thing(2) );

Listing 2-24. variable-output.txt


string(7) "chicken"
string(7) "tractor"
string(8) "vehicles"
string(7) "tractor"
string(8) "vehicles"
PHP Notice:  Undefined variable: get_thing in variable.php on line 41
NULL
string(7) "tractor"
PHP Fatal error:  Uncaught Error: Call to undefined function people() in variable.php:49
Stack trace:
#0 {main}
  thrown in variable.php on line 49

As you can see, the variable $get_thing is just a string holding the name of the function you want to
call, and you can change that name whenever you want. However, the actual functions operate just like
named functions (because that is what they are).

Language Constructs
strtoupper()—that’s a function, right? Yup. How about echo()? It’s got the parentheses like strtoupper(),
and it takes parameters, so it must be a function, right? Sorry, nope! Some PHP “functions” are not actually
functions at all but “language constructs,” built-in parts of the language syntax. You can usually spot these
because even though they accept parameters in parentheses, you don’t have to use parentheses. You
can also read the relevant page in the PHP Manual to discover which they are. Examples of function-like
constructs include echo(), print(), unset(), isset(), empty(), include(), and require(). The distinction
between language constructs and functions matters sometimes. Variable functions, described in the
previous section, will not work with language constructs. See Listing 2-25 and Listing 2-26.

24
Chapter 2 ■ Functional Programming: Key Concepts

Listing 2-25. constructs.php


<?php

$var_func = 'echo';

$var_func('hello world!');

Listing 2-26. constructs-output.php


PHP Fatal error:  Uncaught Error: Call to undefined function echo() in constructs.php:5
Stack trace:
#0 {main}
  thrown in constructs.php on line 5

However, if you do need to treat a construct like a function, then all you need to do is to wrap it up in
your own function, as shown in Listing 2-27 and Listing 2-28.

Listing 2-27. constructs2.php


<?php

function my_echo($string) {

    echo $string;

$var_func = 'my_echo';

$var_func('hello world!');

Listing 2-28. constructs2-output.php


hello world!

Return Values
As you saw in the “Named Functions” section, you can use a return statement to assign a value (or return
value) to your functions. There are several properties of return values that you need to understand to get a
good handle on functions.
If you don’t put a return statement in your function or if the execution path on a particular run doesn’t
hit a return statement, then your function will return NULL. See Listing 2-29 and Listing 2-30.

Listing 2-29. null-return.php


<?php

function reverse($string) {

$string = strrev($string);

}
25
Chapter 2 ■ Functional Programming: Key Concepts

function capitals($string) {

    if ($string != 'banana') {

        $string  = strtoupper($string);

        return $string;

    }

# no return statement
var_dump( reverse('hello') );

# returns a value
var_dump( capitals('peaches') );

# execution flow misses return statement


var_dump( capitals('banana') );

Listing 2-30. null-return-output.txt


NULL
string(7) "PEACHES"
NULL

In the reverse() function, you forgot to return any value at all, so the reversed string didn’t make it
back outside the function. Captials() capitalized the peaches fine, but the bananas didn’t pass through a
code path with a return statement, so you just got a NULL back for your troubles.
In a similar manner, the return statement without a parameter also returns NULL, as shown in
Listing 2-31 and Listing 2-32.

Listing 2-31. null-return2.php


<?php

function fruits($type) {

    if ($type == 'mango') {

        return 'Yummy!';

    } else {

        return;

    }

26
Chapter 2 ■ Functional Programming: Key Concepts

var_dump( fruits('kiwi') );

var_dump( fruits('pomegranate') );

var_dump( fruits('mango') );

Listing 2-32. null-return2-output.txt


NULL
NULL
string(6) "Yummy!"

Calling fruits() on kiwi and pomegranate hits the second return statement without a parameter, so
NULL is returned for them. Mango, possibly the greatest fruit of all time, causes the fruits() function code
path to hit the first return statement, which has the Yummy! string as a parameter, so fruit() returns that
string in this case.
The other point to note about the return statement is that it can occur at any point in the function and
immediately terminates the function execution at that point. See Listing 2-33 and Listing 2-34.

Listing 2-33. return.php


<?php

function my_funct() {

    $a = 23;

    return $a;

    $a = 45;

    return $a;

var_dump( my_funct() );

Listing 2-34. return-output.txt


int(23)

As you can see, the function returns after the first return statement, and the code that sets $a equal to
45 (and the subsequent second return call) is never executed.
To sum up, you need to ensure you’ve done all the processing you need to do before you call return and
make sure all of your code paths hit a return statement before the function finishes.

Lambda/Anonymous Functions
You’ve looked at “traditional” named functions and seen some of their drawbacks. Luckily, from PHP 5.4
onward, you can use anonymous functions in PHP. These are also known as anonymous function literals
or lambda functions in other languages. They are called anonymous functions because, unlike named

27
Chapter 2 ■ Functional Programming: Key Concepts

functions, they don’t have a function name. Your first question is probably, “Well, how do you call them
then?” There are a number of different ways to do that, but it’s helpful first to take a look at how PHP
implements anonymous functions “under the hood.” See Listing 2-35 and Listing 2-36.

Listing 2-35. anon.php


<?php

var_dump(

  # An anonymous function

    function ($a) { return $a; }

);

Listing 2-36. anon-output.txt


object(Closure)#1 (1) {
  ["parameter"]=>
  array(1) {
    ["$a"]=>
    string(10) "<required>"
  }
}

You can see that the function definition is the same as for a named function, but sans the name. Looking
at the var_dump output, you can see that the function is in fact an object (of class Closure, something you’ll
look at later in this chapter).
So, what does that mean? It means you can treat it like any other object in PHP. You can assign it to a
variable, and you can pass it around, destroy it, copy it, and more. But how do you actually call it to get it to
something useful? The straightforward way is to assign it to a variable and then use the methods you learned
about earlier (variable functions and call_user_func) to execute it. PHP can tell from the type of the
variable (a closure object rather than a string) that it is an anonymous function rather than a named function
and knows what to do with it. Let’s look at some examples. See Listing 2-37 and Listing 2-38.

Listing 2-37. call_anon.php


<?php

# create an anonymous function and assign it to a variable


$double = function ($a) { return $a * 2; };

var_dump( $double );

# call the anonymous function


var_dump( $double(4) );

var_dump( call_user_func($double, 8) );

# Copy it to another variable;

$two_times = $double;

28
Chapter 2 ■ Functional Programming: Key Concepts

var_dump( $two_times(4) + $double(6) );

# pass it as a parameter to another function

$numbers = [1,2,3,4];

var_dump( array_map( $two_times, $numbers ) );

# redefine it

$double = function ($a) { return $a * 4; };

var_dump( $double(10) );

# but the earlier copy is definitely a copy not a reference

var_dump( $two_times(10) );

# destroy it

unset($double);

var_dump( $double(9) );

Listing 2-38. call_anon-output.txt


object(Closure)#1 (1) {
  ["parameter"]=>
  array(1) {
    ["$a"]=>
    string(10) "<required>"
  }
}
int(8)
int(16)
int(20)
array(4) {
  [0]=>
  int(2)
  [1]=>
  int(4)
  [2]=>
  int(6)
  [3]=>
  int(8)
}
int(40)
int(20)
PHP Notice:  Undefined variable: double in call_anon.php on line 39
PHP Fatal error:  Uncaught Error: Function name must be a string in call_anon.php:39
Stack trace:
#0 {main}
  thrown in call_anon.php on line 39
29
Chapter 2 ■ Functional Programming: Key Concepts

You don’t always need to assign anonymous functions to a variable to be useful. You can define them as
parameters to other functions, for instance. See Listing 2-39 and Listing 2-40.

Listing 2-39. call_anon2.php


<?php

# Define a function that is assigned to a variable,


# that takes a function as its first parameter
# and a parameter to call that function with as its
# second

$function_caller = function ($function, $parameter) {

    $function($parameter);

};

# Define a named function

function double($a) {

    echo ($a * 2)."\n";

# use the anonymous function to call the named function


# using the Variable Function technique

$function_caller('double', 4);

# this time, define a new anonymous function right in the


# calling parameter code

$function_caller( function($a) { echo 'Function says ' . $a . "\n"; },


    'Hello There');

# Do it again, but with a different anonymous function. Note that


# the anonymous function no longer finishes once the function
# has finished executing.

$function_caller( function($a) { echo $a . ' backwards is '. strrev($a) . "\n"; },


    'Banana');

# It's not only our own functions that can accept inline definitions
# of anonymous functions ...

var_dump(
    array_map( function($a) { return $a * 2; }, [1,2,3,4])
);

30
Chapter 2 ■ Functional Programming: Key Concepts

Listing 2-40. call_anon2-output.txt


8
Function says Hello There
Banana backwards is ananaB
array(4) {
  [0]=>
  int(2)
  [1]=>
  int(4)
  [2]=>
  int(6)
  [3]=>
  int(8)
}

Higher-Order Functions
A higher-order function is a function that can take one or more functions as input and/or return one or more
functions as output, and I touched on them in at the end of the previous section. Higher-order functions
are functions that work on other functions. In functional programming, you’ll look at using higher-order
functions for program control (rather than imperative control statements like for and while).
I’ve covered the building blocks you need for higher-order functions in the previous sections of
this chapter, but if it hasn’t quite clicked with you yet, then consider that you’ve already discovered that
anonymous functions are in fact objects internally in PHP. You’re probably familiar with passing around
traditional objects in PHP, and you can do the same with function objects. They can be used as parameters to
a function and returned as the result of a function. Let’s look at an example; see Listing 2-41 and Listing 2-42.

Listing 2-41. higher-order.php


<?php

# Define some data. I should stop writing code


# when I'm hungry...

$fruits = ['apple', 'banana', 'blueberry', 'cherry'];


$meats = ['antelope','bacon','beef','chicken'];
$cheeses = ['ambert','brie','cheddar','daralagjazsky'];

# Create a function that filters an array and picks out the

# elements beginning with a specified letter

$letter_filter = function($list, $letter) {

  # Rather than a foreach loop or similar, we'll use PHP's


    # higher-order array_filter function. Note it takes two
    # paramters, an array ($list in our case) and a
    # function (which we've defined inline)

    return array_filter($list, function($item) use ($letter)  {

31
Chapter 2 ■ Functional Programming: Key Concepts

        return $item[0] == $letter;

    });

};

# We can call the function on our data as normal.

print_r( $letter_filter($fruits,'a') );
print_r( $letter_filter($meats,'b') );
print_r( $letter_filter($cheeses,'c') );

# But let's use a single call to the higher-level array_map function


# to demonstrate a simple "loop" over three arrays & parameters.
# It should give the same output as the three functions above,
# wrapped up into a single array.

print_r(
    array_map( $letter_filter, [$fruits, $meats, $cheeses], ['a', 'b', 'c'])
);

Listing 2-42. higher-order-output.txt


Array
(
    [0] => apple
)
Array
(
    [1] => bacon
    [2] => beef
)
Array
(
    [2] => cheddar
)
Array
(
    [0] => Array
        (
            [0] => apple
        )

    [1] => Array


        (
            [1] => bacon
            [2] => beef
        )

32
Chapter 2 ■ Functional Programming: Key Concepts

    [2] => Array


        (
            [2] => cheddar
        )

The last array_map clause may give you some hints as to how you can replace loops and other
imperative program control structures using functions.
You may also have spotted that in the anonymous function you used as the last parameter to array_
filter, there was a use ($letter) clause. array_filter doesn’t provide any way for you to pass additional
variables to the filtering function, and $letter is out of the scope of the function when it is executed. use allows
you to bind data to your functions, so you can take advantage of variables that wouldn’t normally be available
to it. I’ll discuss scope in the next section and talk more about the use clause when you look at closures.
It’s not all about consuming functions as input, though; higher-order functions often return them as
output as well. Let’s take a look at an example of that. See Listing 2-43 and Listing 2-44.

Listing 2-43. higher-order2.php


<?php

# Create a higher order function to return a


# function to "add" two variables using a user selectable
# method

function add($method) {

    if ($method == 'sum') {

        # our return value is actually an anonymous function

        return function($a, $b) { return $a+$b;};

    } else {

        # this is returning a different function object

        return function($a, $b) { return $a.$b; };

    }

# Let's call the function. Note, that as the function


# returns a function, we can simply stick an extra
# set of parentheses on the end with some parameters
# to call that newly returned function.

print_r( add('sum')(2,3) ."\n" );


print_r( add('concatenate')('hello ', 'world!') ."\n" );

33
Chapter 2 ■ Functional Programming: Key Concepts

# We can also pass the function to returned to other


# higher order functions like array_map

$a = [1, 2, 'cat', 3, 'orange', 5.4];


$b = [6, 3, 'ch', 9.5, 'ish', 6.5];

print_r( array_map(add('sum'), $a, $b) );


print_r( array_map(add('concatenate'), $a, $b) );

# and we can assign the returned function to a


# variable as with any anonymous function

$conc = add('concatenate');

print_r( array_map($conc, $a, $b) );

print_r( $conc("That's all, ", "folks!\n") );

Listing 2-44. higher-order2-output.txt


5
hello world!
Array
(
    [0] => 7
    [1] => 5
    [2] => 0
    [3] => 12.5
    [4] => 0
    [5] => 11.9
)
Array
(
    [0] => 16
    [1] => 23
    [2] => catch
    [3] => 39.5
    [4] => "orange" and "ish"
    [5] => 5.46.5
)
Array
(
    [0] => 16
    [1] => 23
    [2] => catch
    [3] => 39.5
    [4] => "orange" and "ish"
    [5] => 5.46.5
)
That's all, folks!

34

www.allitebooks.com
Exploring the Variety of Random
Documents with Different Content
something else. Thus the reflection of a person in a mirror is known
as his “image”; in popular usage one person is similarly described as
“the very image” of another; so in entomology the term is applied in
its Latin form imago to an insect which, having passed through its
larval stages, has achieved its full typical development. The term is
in fact susceptible of two opposite connotations; on the one hand, it
implies that the thing to which it is applied is only a copy; on the
other that as a copy it is faithful and accurate.

Psychology (q.v.) recognizes two uses of the term. The simplest is


for the impression made by an observed object on the retina, the
eye; in this connexion the term “after-image” (better “after-
sensation”) is used for an image which remains when the eye is
withdrawn from a brilliantly lighted object; it is called positive when
the colour remains the same, negative when the complementary
colours are seen. The strict psychological use of the term “image” is
by analogy from the physiological for a purely mental idea which is
taken as being observed by the eye of the mind. These images are
created or produced not by an external stimulus, such as is
necessary for a visual image (even the after-image is due to the
continued excitement of the same organ), but by a mental act of
reproduction. The simplest ideational image, which has been
described as the primary memory-image, is “the peculiarly vivid and
definite ideal representation of an object which we can maintain or
recall by a suitable effort of attention immediately after perceiving it”
(Stout). For this no external stimulus is required, and as compared
with the after-image it represents the objects in perspective just as
they might be seen in perception. This is characteristic of all mental
images. The essential requisite for this primary image is that the
attention should have been fixed upon the impressions.
The relation between sense-impressions and mental images is a
highly complicated one. Difference in intensity is not a wholly
satisfactory ground of distinction; abnormal physical conditions
apart, an image may have an intensity far greater than that of a
sense-given impression. On the other hand, Hume is certainly right
in holding that the distinctive character of a percept as compared
with an image is in all ordinary cases the force and liveliness with
which it strikes the mind—the distinction, therefore, being one of
quality, not of degree. A distinction of some importance is found in
the “superior steadiness” (Ward) of impressions; while looking at any
set of surroundings, images of many different scenes may pass
through the mind, each one of which is immediately distinguished
from the impression of the actual scene before the eyes. This arises
partly, no doubt, from the fact that the perception has clear
localization, which the image has not. In many cases indeed an
image even of a most familiar scene is exceedingly vague and
inaccurate.

In Art the term is used for a representation or likeness of an


animate or inanimate object, particularly of the figure of a person in
sculpture or painting. The most general application of the word is to
such a representation when used as an object of religious worship or
adoration, or as a decorative or architectural ornament in places of
religious worship. The worship of images, or idolatry, from the point
of view of comparative religion, is treated in the article Image-
Worship, and the history of the attitude of the Christian church,
outside the post-Reformation church of England, towards the use of
images as objects of worship and religion in the article Iconoclasts.
With regard to the Pre-Reformation period in England, it is of
interest to note that by the constitutions of Archbishop Winchelsey,
1305, it was the duty of the parish to provide for the parish church,
among other objects, the images of Christ on the Cross, of the saint
to whom the church was dedicated, to be placed in the chancel, and
of other saints. The injunctions of Edward VI., 1547, ordered the
destruction of all images that had been the objects of superstitious
use, and the act of 1549 (3 & 4 Edw. VI. c. 10) declared all such
images illegal. This act, repealed in Mary’s reign, was revived in
1604 (1 James I. c. 25) and is still in force. The present effect of this
unrepealed act, as stated in Boyd v. Philpotts (L.R. 6 P.C. 449), is
that it only referred to the images then subject to abuse, which had
been ordered to be removed, and did not refer to the subsequent
use or abuse of other images. In Article XXII. of the Articles of
Religion it is laid down that “the Romish Doctrine concerning ...
Worshipping and Adoration as well of Images as of Reliques ... is a
fond thing mainly invented and grounded on no warranty of
Scripture, but rather repugnant to the Word of God.” The law in
regard to images, which in this connexion include pictures and
stained-glass windows, but not sculptured effigies on monuments or
merely ornamental work, is contained in various judicial decisions,
and is not defined by statute. The effect of these decisions is thus
summarized in the report of the Royal Commission on Ecclesiastical
Discipline, 1906: “Such images are lawful as objects of decoration in
a church, but are unlawful if they are made, or are in danger of
being made, objects of superstitious reverence, contrary to Article
XXII. against the worshipping and adoration of images. In
accordance with this view, crosses, if not placed on the Holy Table,
and also crucifixes, if part only of a sculptured design or architectural
decoration, have been declared lawful. The question whether a
crucifix or rood standing alone or combined with figures of the
Blessed Virgin and St John can, in any circumstances, be regarded
as merely decorative, has given rise to a difference of judicial
opinion and appears to be unsettled.” Speaking generally, articles of
decoration and embellishment not used in the services cannot
lawfully be introduced into a church without the consent of the
ordinary given by a faculty, the granting of which is subject to the
judicial discretion of the chancellor or commissary, sitting as judge of
the bishop’s court. By section 8 of the Public Worship Regulation Act
1874, complainants may take proceedings if it is considered that
“any alteration in, or addition to, the fabric, ornaments or furniture
has been made without legal authority, or that any decoration
forbidden by law has been introduced into such church ... provided
that no proceedings shall be taken ... if such alteration or addition
has been completed five years before the commencement of such
proceedings.” The following are the principal cases on the subject: in
Boyd v. Philpotts, 1874 (L.R., 4 Ad. & Ec. 297; 6 P.C. 435), the
Exeter reredos case, the privy council, reversing the bishop’s
judgment, allowed the structure, which contained sculptures in high
relief of the Ascension, Transfiguration and Descent of the Holy
Ghost at Pentecost, together with a cross and angels; in R. v. the
Bishop of London, 1889 (23 Q.B.D. 414, 24 Q.B.D. 213), the St
Paul’s reredos case, the bishop refused further proceedings against
the legality of a structure containing sculptured figures of Christ on
the Cross and the Virgin and Child. In Clifton v. Ridsdale, 1876 (1 P.
& D., 316), a metal crucifix on the centre of the chancel screen was
declared illegal as being in danger of being used superstitiously, and
in the same case pictures or rather coloured reliefs representing the
“Stations of the Cross” were ordered to be removed on the ground
that they had been erected without a faculty, and were also
considered unlawful by Lord Penzance as connected with certain
superstitious devotion authorized by the Roman church.
IMAGE WORSHIP. It is obvious that two religious votaries
kneeling together before a statue may entertain widely different
conceptions of what the image is and signifies, although their
outward attitude is the same. The one may regard it as a mere
image, picture or representation of the higher being, void in itself of
value or power. It is to him, like the photograph hung on a wall of
one we love, cherished as a picture and no more. But the other may
regard it, as a little girl regards her doll, as an animated being, no
mere picture, but as tenement and vehicle of the god and fraught
with divine influence. The former is the attitude which the Latin
Church officially inculcates towards sacred pictures and statues; they
are intended to convey to the eyes of the faithful, especially to the
illiterate among them, the history of Jesus, of the Virgin and of the
saints. The other attitude, however, is that into which simple-minded
Latin peasants actually lapse, as it is also that which characterizes
other religions ancient or modern which use pictures or sculptures of
gods, demons, men, brutes, or of particular parts and organs of the
same. With the latter attitude alone does the present article deal,
and it may conveniently be called idolatry or image worship. For the
history of the use of images in Christian worship see Iconoclasts.

The image or idol differs from the fetish, charm, talisman,


phylactery or miraculous relic, only in this, that either in the flat or
the round it resembles the power adored; it has a prototype capable
of being brought before the eye and visualized. This is not
necessarily the case with the worshipper of aniconic or unshaped
gods. The Semite or savage who sets up a sacred stone or Bethel
believes indeed that a divine power or influence enters the stone
and dwells in it, and he treats the stone as if it were the god, kisses
it, anoints it with oil, feeds the god in it by pouring out over it the
blood of victims slain. But he is not an idolater, for he has not “made
unto himself any graven image, nor the likeness of anything that is
in heaven above or in the water beneath or in the water under the
earth.”

The question arises: must the stage of aniconic gods historically


precede and lead up to that of pictures and images? Are the latter a
development of the former? In the history of human religions can we
trace, as it were, a law of transition from sacred stock and stone up
to picture and image? Is it true to say that the latter is characteristic
of a later and higher stage of religious development? It was perhaps
the facility with which a pillar of stone or wood can be turned into an
image by painting or sculpturing on it eyes, ears, mouth, marks of
sex and so on, which led anthropologists of an earlier generation to
postulate such a law of development; but facts do not bear it out. In
the first place, what we are accustomed to call higher religions
deliberately attach greater sanctity to aniconic gods than to iconic
ones, and that from no artistic incapacity. The Jews were as well
able as their neighbours to fashion golden calves, snakes and the
minor idols called teraphim, when their legislator, in the words we
have just cited, forbade the ancillary use of all plastic and pictorial
art for religious purposes. And of our own Christianity, Robertson
Smith remarks as follows: “The host in the Mass is artistically as
much inferior to the Venus of Milo as a Semitic Maṣṣēba was, but no
one will say that medieval Christianity is a lower form of religion than
Aphrodite worship.”

Here then in the most marked manner the aniconic sacrament has
ousted pictures and statues. It is the embodiment and home of
divine personality and power, and not they. Equally contradictory of
any such law of development is the circumstance that the Greeks of
the 5th and 4th centuries b.c., although Pheidias and other artists
were embodying their gods and goddesses in the most perfect of
images, nevertheless continued to cherish the rude aniconic stocks
and stones of their ancestors. If any such law ever operated in
human religious development, how can we explain the following
facts. In the shadowy age which preceded the Stone age and hardly
ended later than 10,000 b.c., the cave-dwellers of the Dordogne
could draw elks, bisons, elephants and other animals at rest or in
movement, with a freshness and realism which to-day only a
Landseer can rival. And yet in the European Stone age which
followed, the age in which the great menhirs and cromlechs were
erected, in which the domestication of animals began and the first
corn was sown, we find in the strata no image of man or beast, big
or little.

Whence this seeming blight and decay of art? Salomon Reinach,


guided by the analogy of similar practices among the aborigines of
Australia, and noticing that these primitive pictures represent none
but animals that formed the staple food of the age and place, and
that they are usually found in the deepest and darkest recesses of
the caves where they could only be drawn and seen by torchlight,
has argued that they were not intended for artistic gratification (a
late motive in human art), but were magical representations
destined to influence and perhaps attract the hunter’s quarry. In a
word this earliest art was ancillary to the chase. It is a common
practice in the magic of all ages and countries to acquire control and
influence over men and animals by making images of them. The
prototype is believed to suffer whatever is done to the image.
Reinach, therefore, supposes that in the Stone age which succeeded,
pictorial art was banned because it had got into the hands of
magicians and had come to be regarded as inevitably uncanny and
malefic. This is certainly the secret of the ordinary Mahommedan
prohibition of pictures and statues, which goes even to the length of
denying to poor little Arab girls the enjoyment of having dolls. It is
felt that if you have got a picture of any one, you have some power
of harming him through it; you can bind or loose him, just as you
can a Djinn whose name you have somehow learned. It is as
dangerous for your enemy to have a picture of you as for him to
know your name. The old Hebrew prohibition of graven images was
surely based on a like superstition, so far as it was not merely due to
the physical impossibility for nomads of heavy statues that do not
admit of being carried from camp to camp and from pasture to
pasture. Possessing no images of Yahweh the Jews were also not
exposed to the same risk as were idolaters of having their gods
stolen by their foes and used against them. Lastly, the restriction to
aniconic worship saved them from much superstition, for there is
nothing which so much stimulates the growth of a mythology as the
manufacture of idols. The artist must indeed start with imaginative
types, revealed to him in visions or borrowed from current myths.
But the tendency of his art is to give rise to new tales of the gods.
There is perpetual action and reaction between picture and myth;
and a legislator desiring to purify and raise his countrymen’s religion
must devote no less attention to their plastic art than to their
hymnology.

Motives drawn from homoeopathic magic may thus explain the


occasional disuse and prohibition of pictorial and plastic art in cult;
they may equally explain its genesis and rise in certain ages and
countries. Prayer is much more hopeful and efficacious for a
worshipper who has means of bringing near to himself, and even
coercing the god he worships. An image fashioned like a god, and
which has this advantage over a mere stock and stone that it
declares itself and reveals at a glance to what god it is sacred, must
surely attract and influence the god to choose it as his home and
tenement. And having the god thus at hand and imprisoned in
matter, the simple-minded worshipper can punish him if his prayers
are left unanswered. Dr E. B. Tylor accordingly (in his chapter on
“Idolatry” in Primitive Culture, ii. 170), reminds us of “the negro who
feeds ancestral images and brings them a share of his trade profits,
but will beat an idol or fling it into the fire if it cannot give him luck
or preserve him from sickness.” So Augustus Caesar, having lost
some ships in a storm, punished Neptune by forbidding his image to
be carried in procession at the Circensian games (Sueton. Aug. 16).

In certain cases the wish to carry elsewhere the cult of a favourite


or ancestral cult, may have dictated the manufacture of images that
declare themselves and reveal at a glance whose they are. Thus a
Phoenician colonist might desire to carry abroad the cult of a certain
Baal or Astarte who lived in a conical stone or pillar. Pilgrims visiting
Paphos, the original home and temple of Astarte, could of course be
in no doubt about which of the heavenly powers inhabited the cone
of stone in which she was there held to be immanent; nor was any
Semite ever ignorant as to which Baal he stood before. It was
necessarily the Baal or Lord of the region. But small portrait statues
must surely have been made to be carried about or used in private
worship. Meanwhile the shapeless cone remained the object of
public adoration and pilgrimage.

The Egyptian writer Hermes Trismegistus (c. 250), in a work called


Asclepius (cited by Augustine, De civit. Dei, viii. 26), claims that his
ancestors discovered the art of making gods, and since they could
not create souls, they called up the souls of demons or angels and
introduced them into the holy images and divine mysteries, that
through these souls the idols might possess powers of doing good
and harm. This was the belief of the pagans, and the Christians for
centuries shared it with them. Not a few Christian martyrs sought
and won the palm by smashing the idols in order to dislodge the
indwelling devil; occasionally their zeal was further gratified by
beholding it pass away like smoke from its ruined home.

Image worship then is a sort of animism. It is a continuance by


adults of their childish games with dolls. In the Roman religion, on a
feast of thanksgiving for a great victory, couches were spread in the
temples for the gods, whose images were taken down from their
pedestals and laid on the couches, and tables set before them
loaded with delicate viands. This was called a Lectisternium. So
Marco Polo (i. chap. 53) relates how the Tatars had each a figure of
Natigay, the god of the earth, who watched over their children,
cattle and crops. The image was made of felt and cloth, and similar
images of his wife and children were set on his left hand and in front
of him. “And when they eat, they take the fat of the meat and
grease the god’s mouth withal, as well as the mouths of his wife and
children.” The old Greek statues moved of themselves, shook their
spears, kneeled down, spoke, walked, wept, laughed, winked, and
even bled and sweated,—a mighty portent. Images of Christ, of the
Virgin and saints have achieved many a similar miraculous portent. A
figure of Christ has been known even to give its shoes to a poor
man, and a Virgin to drop a ring off her finger to a suppliant. In
Umbrian villages on Easter Sunday the images of Jesus and His
Mother are carried in rival processions from their respective chapels,
and are made to bow when they meet face to face. The spectators
applaud or hiss according as they make their bow well or ill. In
antiquity it was a common ceremony to arrange a holy marriage
between male and female images, and such unions acted on the
earth as a fertility charm. Much of a priest’s time was given up to the
toilet of the god or goddess. Thus Isis was dressed and coiffed every
day by her special attendants according to Apuleius (Met. xi. 9). Like
the statue of St Agatha of Catania to-day, her image was loaded
with jewels, and an inscription of Cadiz (C.I.L. ii. 3386) contains an
inventory of the jewels with which Isis had been endowed by
Spanish devotees.

Idolatrous cults repose so largely on make-believe and credulity


that the priests who administered them, perhaps oftener than we
know, fell into the kind of imposture and trickery of which the legend
of Bel and the dragon represents a classical example. “Thinkest thou
not,” said King Astyages, “that Bel is a living god? Or seest thou not
how much he eateth and drinketh every day? Then Daniel laughed,
and said, O King, be not deceived: for this is but clay within, and
brass without, and did never eat or drink anything.” In the sequel
Daniel proves to the king that the priests with their wives and
children came in through privy doors and consumed the viands set
before the god; and the king, angered at their trickery, slew them all
and gave Bel over to Daniel for destruction.

The invectives against idolatry of the early Jewish and Christian


apologists, of Philo, Minucius Felix, Tertullian, Arnobius, Lactantius
and others, are very good reading and throw much light on the
question how an ancient pagan conceived of his idols. One capital
argument of the Christians was the absurdity of a man making an
idol and then being afraid of or adoring the work of his own hands.
Lactantius preserves the answer of the pagans so attacked (De
origine Erroris, ii. 2): We do not, they said, fear the images
themselves, but those beings after whose likeness they were
fashioned and by whose names they were consecrated. Few such
rites of consecration remain, but they must have been similar to
those used in India to-day. There the Brahmin invites the god to
dwell within the image, specially made hollow to contain him,
“performing the ceremony of adhivāsa or inhabitation, after which
he puts in the eyes and the prāna, i.e. breath, life or soul.”1 Similarly
Augustine (De civ. Dei, viii. 23) relates how, according to Hermes,
the spirits entered by invitation (spiritus invitatos), so that the
images became bodies of the gods (corpora deorum). Thus the
invisible spirits by a certain art are so joined unto the visible objects
of corporeal matter that the latter become as it were animated
bodies, images dedicated to those spirits and controlled by them
(see Consecration). Such statues were animated with sense and full
of spirit, they foresaw the future, and foretold it by lot, through their
priests, in dreams and in other ways.

See E. B. Tylor, Primitive Culture, ed. 1903 (list of authorities


and sources vol., p. 171); L. R. Farnell, The Evolution of Religion
(London, 1905); Jacob Grimm, Teutonic Mythology, translation
by J. S. Stallybrass.
(F. C. C.)

1 Tylor, Prim. Culture, ii. 178.

IMAGINATION, in general, the power or process of producing


mental pictures or ideas. The term is technically used in psychology
for the process of reviving in the mind percepts of objects formerly
given in sense perception. Since this use of the term conflicts with
that of ordinary language, some psychologists have preferred to
describe this process as “imaging” or “imagery” or to speak of it as
“reproductive” as opposed to “productive” or “constructive”
imagination (see Image and Psychology). The common use of the term
is for the process of forming in the mind new images which have not
been previously experienced, or at least only partially or in different
combinations. Thus the image of a centaur is the result of combining
the common percepts of man and horse: fairy tales and fiction
generally are the result of this process of combination. Imagination
in this sense, not being limited to the acquisition of exact knowledge
by the requirements of practical necessity, is up to a certain point
free from objective restraints. In various spheres, however, even
imagination is in practice limited: thus a man whose imaginations do
violence to the elementary laws of thought, or to the necessary
principles of practical possibility, or to the reasonable probabilities of
a given case is regarded as insane. The same limitations beset
imagination in the field of scientific hypothesis. Progress in scientific
research is due largely to provisional explanations which are
constructed by imagination, but such hypotheses must be framed in
relation to previously ascertained facts and in accordance with the
principles of the particular science. In spite, however, of these broad
practical considerations, imagination differs fundamentally from
belief in that the latter involves “objective control of subjective
activity” (Stout). The play of imagination, apart from the obvious
limitations (e.g. of avoiding explicit self-contradiction), is conditioned
only by the general trend of the mind at a given moment. Belief, on
the other hand, is immediately related to practical activity: it is
perfectly possible to imagine myself a millionaire, but unless I
believe it I do not, therefore, act as such. Belief always endeavours
to conform to objective conditions; though it is from one point of
view subjective it is also objectively conditioned, whereas
imagination as such is specifically free. The dividing line between
imagination and belief varies widely in different stages of mental
development. Thus a savage who is ill frames an ideal reconstruction
of the causes of his illness, and attributes it to the hostile magic of
an enemy. In ignorance of pathology he is satisfied with this
explanation, and actually believes in it, whereas such a hypothesis in
the mind of civilized man would be treated as a pure effort of
imagination, or even as a hallucination. It follows that the distinction
between imagination and belief depends in practice on knowledge,
social environment, training and the like.

Although, however, the absence of objective restraint, i.e. a


certain unreality, is characteristic of imagination, none the less it has
great practical importance as a purely ideational activity. Its very
freedom from objective limitation makes it a source of pleasure and
pain. A person of vivid imagination suffers acutely from the
imagination of perils besetting a friend. In fact in some cases the
ideal construction is so “real” that specific physical manifestations
occur, as though imagination had passed into belief or the events
imagined were actually in progress.

IMĀM, an Arabic word, meaning “leader” or “guide” in the sense


of a “pattern whose example is followed, whether for good or bad.”
Thus it is applied to the Koran, to a builder’s level and plumb-line, to
a road, to a school-boy’s daily task, to a written record. It is used in
several of these, senses in the Koran, but specifically several times
of leaders and (ii. 118) of Abraham, “Lo, I make thee a pattern for
mankind.” Imām thus became the name of the head of the Moslem
community, whose leadership and patternhood, as in the case of
Mahomet himself, is to be regarded as of the widest description. His
duty is to be the lieutenant, the Caliph (q.v.) of the Prophet, to
guard the faith and maintain the government of the state. Round the
origin and basis of his office all controversies as to the Moslem state
centre. The Sunnites hold that it is for men to appoint and that the
basis is obedience to the general usage of the Moslem peoples from
the earliest times. The necessity for leaders has always been
recognized, and a leader has always been appointed. The basis is
thus agreement in the technical sense (see Mahommedan Law), not
Koran nor tradition from Mahomet nor analogy. The Shī’ites in
general hold that the appointment lies with God, through the
Prophet or otherwise, and that He always has appointed. The
Khārijites theoretically recognize no absolute need of an Imām; he is
convenient and allowable. The Motazilites held that reason, not
agreement, dictated the appointment. Another distinction between
the Sunnites and the Shī’ites is that the Sunnites regard the Imām
as liable to err, and to be obeyed even though he personally sins,
provided he maintains the ordinances of Islām. Effective leadership
is the essential point. But the Shī’ites believe that the divinely
appointed Imām is also divinely illumined and preserved (ma‘ṣūm)
from sin. The above is called the greater Imāmate. The lesser
Imāmate is the leadership in the Friday prayers. This was originally
performed by the Imām in the first sense, who not only led in
prayers but delivered a sermon (khuṭba); but with the growth of the
Moslem empire and the retirement of the caliph from public life, it
was necessarily given over to a deputy—part of a gradual process of
putting the Imāmate or caliphate into commission. These deputy
Imāms are, in Turkey, ministers of the state, each in charge of his
own parish; they issue passports, &c., and perform the rites of
circumcision, marriage and burial. In Persia among Shī’ites their
position is more purely spiritual, and they are independent of the
state. A few of their leaders are called Mujtahids, i.e. capable of
giving an independent opinion on questions of religion and canon
law. A third use of the term Imām is as an honorary title. It is thus
applied to leading theologians, e.g. to Abū Ḥanīfa, ash-Shāfi‘ī, Malik
ibn Anas, Aḥmad ibn Ḥanbal (these are called “the four Imāms”),
Ghazāli.

See McG. de Slane’s transl. of Ibn Khaldūn’s Prolégomènes, i.


384 seq., 402 seq., 426 seq., 445; iii. 35, 58 seq.; Ostrorog’s
transl. of Māwardī’s Ahkām i. 89 seq.; Haarbrücker’s transl. of
Shahrastānī by index; Juynboll’s De Mohammedanische Wet, 316
seq.; Sell’s Faith of Islam, 95 seq.; Macdonald’s Development of
Muslim Theology, 56 seq.
(D. B. Ma.)

IMBECILE (through the French from Lat. imbecillus or imbecillis,


weak, feeble; of unknown origin), weak or feeble, particularly in
mind. The term “imbecility” is used conventionally of a condition of
mental degeneration less profound than “idiotcy” (see Insanity).
IMBREX (Latin for “tile”), in architecture the term given to the
covering tile of the ancient roof: the plain tile is turned up on each
side and the imbrex covers the joint. In the simpler type of roof the
imbrex is semicircular, but in some of the Greek temples it has
vertical sides and an angular top. In the temple of Apollo at Bassae,
where the tiles were in Parian marble, the imbrex on one side of the
tile and the tile were worked in one piece out of the solid marble.

IMBROS, a Turkish island in the Aegean, at the southern end of


the Thracian Chersonese peninsula. It forms with Samothrace, about
17 m. distant, a caza (or canton) in the sanjak of Lemnos and
province of the Archipelago Isles. Herodotus (v. 26) mentions it as
an abode of the historic Pelasgians (q.v.). It was, like Samothrace, a
seat of the worship of the Cabeiri (q.v.). The island is now the seat
of a Greek bishopric. There is communication with the mainland by
occasional vessels. The island is of great fertility—wheat, oats,
barley, olives, sesame and valonia being the principal products, in
addition to a variety of fruits. Pop. about 92,000, nearly all Turks.

IMERETIA, or Imeritia a district in Russian Transcaucasia, extends


from the left bank of the river Tskheniz-Tskhali to the Suram range,
which separates it from Georgia on the east, and is bounded on the
south by Akhaltsikh, and thus corresponds roughly to the eastern
part of the modern government of Kutais. Anciently a part of Colchis,
and included in Lazia during the Roman empire, Imeretia was
nominally under the dominion of the Greek emperors. In the early
part of the 6th century it became the theatre of wars between the
Byzantine emperor Justinian and Chosroes, or Khosrau, king of
Persia. Between 750 and 985 it was ruled by a dynasty (Apkhaz) of
native princes, but was devastated by hostile incursions, reviving
only after it became united to Georgia. It flourished until the reign of
Queen Thamar, but after her death (1212) the country became
impoverished through strife and internal dissensions. It was reunited
with Georgia from 1318 to 1346, and again in 1424. But the union
only lasted forty-five years; from 1469 until 1810 it was governed by
a Bagratid dynasty, closely akin to that which ruled over Georgia. In
1621 it made the earliest appeal to Russia for aid; in 1650 it
acknowledged Russian suzerainty and in 1769 a Russian force
expelled the Turks. In 1803 the monarch declared himself a vassal of
Russia, and in 1810 the little kingdom was definitively annexed to
that empire. (See Georgia.)

IMIDAZOLES, or Glyoxalines, organic chemical compounds


containing the ring system Imidazole itself was first

prepared by H. Debus (Ann. 1858, 107, p. 254) by the action of


ammonia on glyoxal, 2C2H2O2 + 2NH3 = C3H4N2 + H2CO2 + 2H2O.
The compounds of this series may be prepared by the condensation
of ortho-diketones with ammonia and aldehydes

from thioimidazolones by oxidation with dilute nitric acid (W.


Marckwald, Ber., 1892, 25, p. 2361); by distillation of
hydrobenzamide and similarly constituted bodies; and by the action
of phosphorus pentachloride on symmetrical dimethyloxamide, a
methylchlorglyoxaline being formed (O. Wallach, Ann., 1877, 184, p.
500).

The glyoxalines are basic in character, and the imide hydrogen is


replaceable by metals and alkyl groups. They are stable towards
reducing agents, and acidyl groups are only introduced with
difficulty.

Imidazole (glyoxaline), C3H4N2, crystallizes in thick prisms


which melt at 88-89° C. and boil at 253° C., and are readily
soluble in alcohol and in water. It is unaffected by chromic acid,
but potassium permanganate oxidizes it to formic acid. It forms
salts with acids.

Lophine (triphenylglyoxaline), is formed

by the dry distillation of hydrobenzamide, or by saturating an


alcoholic solution of benzil and benzaldehyde (at a temperature
of 40° C.) with ammonia. It crystallizes in needles which melt at
275° C. It is a weak base. When heated to 300° C. with
hydriodic acid and hydrochloric acid, in the presence of some
red phosphorus, it yields benzoic acid.

The keto-glyoxalines are known as imidazolones and are


prepared by the action of acids on acetalyl thioureas (W.
Marckwald, Ber., 1892, 25, p. 2357). Benzimidazole,
is the simplest representative of the
benzoglyoxalines and is prepared by the condensation of formic
acid with ortho-phenylene diamine. It forms rhombic crystals
which melt at 170° C. It is basic in character, and on oxidation
with potassium permanganate yields a small amount of
glyoxaline dicarboxylic acid, (E. Bamberger,

Ann., 1893, 273, p. 338).

IMITATION (Lat. imitatio, from imitari, to imitate), the


reproduction or repetition of an action or thought as observed in
another person or in oneself, or the construction of one object in the
likeness of another. By some writers (e.g. Preyer and Lloyd Morgan)
the term “imitation” is limited to cases in which one person copies
the action or thought of another; others have preferred a wider use
of the term (i.e. including “self-imitation”), and have attempted to
classify imitative action into various groupings, e.g. as cases of
“conscious imitation,” “imitative suggestion,” “plastic imitation” (as
when the members of a crowd subconsciously reproduce one
another’s modes of thought and action), and the like. The main
distinction is that which takes into account the question of attention
(q.v.). In conscious imitation, the attention is fixed on the act and its
reproduction: in unconscious imitation the reproduction is entirely
mechanical and the agent does not “attend” to the action or thought
which he is copying: in subconscious imitation the action is not
deliberate, though the necessary train of thought would immediately
follow if the attention were turned upon it under normal conditions.
Imitation plays an extremely important part in human and animal
development, and a clear understanding of its character is important
both for the study of primitive peoples, and also in the theories of
education, art and sociology. The child’s early development is in
large measure imitative: thus the first articulate sounds and the first
movements are mainly reproductions of the words and actions of
parents, and even in the later stages that teacher is likely to achieve
the best results who himself gives examples of how a word should
be pronounced or an action done. The impulse to imitate is,
however, not confined to children: there is among the majority of
adults a tendency to assimilate themselves either to their society or
to those whom they especially admire or respect: this tendency to
shun the eccentric is rooted deeply in human psychology. Moreover,
even among highly developed persons the imitative impulse
frequently overrides the reason, as when an audience, a crowd, or
even practically a whole community is carried away by a panic for
which no adequate ground has been given, or when a cough or a
yawn is imitated by a company of people. Such cases may be
compared with those of persons in mesmeric trances who
mechanically copy a series of movements made by the mesmerist.
The universality of the imitative impulse has led many psychologists
to regard it as an instinct (so William James, Principles of
Psychology, ii. 408; cf. Instinct), and in that large class of imitative
actions which have no obvious ulterior purpose the impulse certainly
appears to be instinctive in character. On the other hand where the
imitator recognizes the particular effect of a process and imitates
with the deliberate intention of producing the same effect, his action
can scarcely be classed as instinctive. A considerable number of
psychologists have distinguished imitative from instinctive actions
(e.g. Baldwin, and Sully). According to Darwin the imitative impulse
begins in infants at the age of four months. It is to be noted,
however, that the child imitates, not every action indiscriminately,
but especially those towards which it has a congenital tendency. The
same is true of animals: though different kinds of animals may live in
close proximity, the young of each kind imitate primarily the actions
of their own parents.

Among primitive man imitation plays a very important part. The


savage believes that he can bring about events by imitating them.
He makes, for instance, an image of his enemy and pierces it with
darts or burns it, believing that by so doing he will cause his enemy’s
death: similarly sailors would whistle, or farmers would pour water
on the ground, in the hope of producing wind or rain. This form of
imitation is known as sympathetic magic (see Magic). The
sociological importance of imitation is elaborately investigated by
Gabriel Tarde (Les Lois de l’imitation, 2nd ed., 1895), who bases all
social evolution on the imitative impulse. He distinguishes “custom
imitations,” i.e. imitations of ancient or even forgotten actions, and
“mode imitations,” i.e. imitations of current fashions. New discoveries
are, in his scheme, the product of the conflict of imitations. This
theory, though of great value, seems to neglect original natural
similarities which, by the law of causation, produce similar
consequences, where imitation is geographically or chronologically
impossible.
The term “imitation” has also the following special uses:—

1. In Art-theory.—According to Plato all artistic production is a


form of imitation (μίμησις). That which really exists is the idea or
type created by God; of this type all concrete objects are
representations, while the painter, the tragedian, the musician are
merely imitators, thrice removed from the truth (Rep. x. 596 seq.).
Such persons are represented by Plato as a menace to the moral
fibre of the community (Rep. iii.), as performing no useful function,
drawing men away from reality and pandering to the irrational side
of the soul. All art should aim at moral improvement. Plato clearly
intends by “imitation” more than is connotated by the modern word:
though in general he associates with it all that is bad and second-
rate, he in some passages admits the value of the imitation of that
which is good, and thus assigns to it a certain symbolic significance.
Aristotle, likewise regarding art as imitation, emphasizes its purely
artistic value as purging the emotions (κάθαρσις), and producing
beautiful things as such (see Aesthetics and Fine Arts).

2. In Biology, the term is sometimes applied to the assimilation by


one species of certain external characteristics (especially colour)
which enable them to escape the notice of other species which
would otherwise prey upon them. It is a form of protective
resemblance and is generally known as mimicry (q.v.; see also
Colours of Animals).

3. In Music, the term “imitation” is applied in contrapuntal


composition to the repetition of a passage in one or more of the
other voices or parts of a composition. When the repetition is note
for note with all the intervals the same, the imitation is called “strict”
and becomes a canon (q.v.); if not it is called “free,” the latter being
much the more common. There are many varieties of imitation,
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like