anonymous functions in php 5.3 - matthew weier o’phinney

72
Anonymous Functions in PHP 5.3 Matthew Weier O’Phinney 26 April 2011

Upload: valery-cheban

Post on 07-Jul-2015

2.653 views

Category:

Technology


0 download

DESCRIPTION

Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney 26 April 2011 http://static.zend.com/topics/slides.pdf

TRANSCRIPT

Page 1: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Anonymous Functions in PHP 5.3

Matthew Weier O’Phinney

26 April 2011

Page 2: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

But first, some vocabulary

Page 3: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Lambdas

26 April 2011 Anonymous Functions in PHP 5.3 3

• From “lambda calculus”

Page 4: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Lambdas

26 April 2011 Anonymous Functions in PHP 5.3 3

• From “lambda calculus”• Names of functions are merely a “convenience”, and

hence all functions are considered anonymous

Page 5: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Lambdas

26 April 2011 Anonymous Functions in PHP 5.3 3

• From “lambda calculus”• Names of functions are merely a “convenience”, and

hence all functions are considered anonymous• Unless you’re using a true functional programming

language with first-class functions, most likely you’resimply using anonymous functions, or lambdaexpressions.

Page 6: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Closures

26 April 2011 Anonymous Functions in PHP 5.3 4

• A function which includes a referencing environment

Page 7: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Closures

26 April 2011 Anonymous Functions in PHP 5.3 4

• A function which includes a referencing environment

• Each function has its own scope• Allows hiding state

Page 8: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Closures

26 April 2011 Anonymous Functions in PHP 5.3 4

• A function which includes a referencing environment

• Each function has its own scope• Allows hiding state

• Differentiating factor is that closures allow bindingreferences that exist at the time of creation, to usewhen called.

Page 9: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Anonymous Functions

26 April 2011 Anonymous Functions in PHP 5.3 5

• Any function defined and/or called without beingbound to an identifier.

• You can assign the function to a variable, butyou’re not giving it its own name.

Page 10: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

PHP’s Offering

Page 11: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Functors

26 April 2011 Anonymous Functions in PHP 5.3 7

• Any object defining a __invoke() method.• Object instances can now be called as if they were

functions.

class Command{

public function __invoke($name){

echo "Hello, $name";}

}$c = new Command();$c(’Matthew’); // "Hello, Matthew"

Page 12: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Anonymous Functions

26 April 2011 Anonymous Functions in PHP 5.3 8

• new Closure class, which defines __invoke().

Page 13: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Anonymous Functions

26 April 2011 Anonymous Functions in PHP 5.3 8

• new Closure class, which defines __invoke().• __invoke() body is “replaced” with the defined

function.

Page 14: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Anonymous Functions

26 April 2011 Anonymous Functions in PHP 5.3 8

• new Closure class, which defines __invoke().• __invoke() body is “replaced” with the defined

function.• Ability to bind variables via imports, allowing creation

of closures.

Page 15: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Important to know:

26 April 2011 Anonymous Functions in PHP 5.3 9

• Just like normal PHP functions, anonymousfunctions exist in their own scope.

Page 16: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Important to know:

26 April 2011 Anonymous Functions in PHP 5.3 9

• Just like normal PHP functions, anonymousfunctions exist in their own scope.

• You cannot import $this.

Page 17: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Important to know:

26 April 2011 Anonymous Functions in PHP 5.3 9

• Just like normal PHP functions, anonymousfunctions exist in their own scope.

• You cannot import $this.• You cannot alias imported variables.

Page 18: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Anonymous Function andClosure Syntax

Page 19: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Basics

26 April 2011 Anonymous Functions in PHP 5.3 11

• Simply like normal function declaration, except noname:

function($value1[, $value2[, ... $valueN]]) { };

Page 20: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Assign to variables

26 April 2011 Anonymous Functions in PHP 5.3 12

• Assign functions to variables; don’t forget thesemicolon terminator!

$greet = function($name) {echo "Hello, $name";

};

$greet(’Matthew’); // "Hello, Matthew"

Page 21: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Pass as arguments to other callables

26 April 2011 Anonymous Functions in PHP 5.3 13

• Allow other functionality to call the function.

function say($value, $callback){

echo $callback($value);}

say(’Matthew’, function($name) {return "Hello, $name";

}); // "Hello, Matthew"

Page 22: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Create closures

26 April 2011 Anonymous Functions in PHP 5.3 14

• Bind variables at creation, and use them at call-time.

$log = Zend_Log::factory($config);

$logger = function() use($log) {$args = func_get_args();$log->info(json_encode($args));

};

$logger(’foo’, ’bar’); // ["foo", "bar"]

Page 23: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Things to try

Page 24: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Array operations

26 April 2011 Anonymous Functions in PHP 5.3 16

• Sorting (usort, uasort, etc.)• Walking, mapping, reducing• Filtering

Page 25: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Sorting

26 April 2011 Anonymous Functions in PHP 5.3 17

$stuff = array(’apple’, ’Anise’, ’Applesauce’, ’appleseed’);usort($stuff, function($a, $b) {

return strcasecmp($a, $b);});// ’Anise’, ’apple’, ’Applesauce’, ’appleseed’

Page 26: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Walking

26 April 2011 Anonymous Functions in PHP 5.3 18

• Walking allows you to change the values of an array.

Page 27: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Walking

26 April 2011 Anonymous Functions in PHP 5.3 18

• Walking allows you to change the values of an array.• If not using objects, then you need to pass by

reference in order to alter values.

$stuff = array(’apple’, ’Anise’, ’Applesauce’, ’appleseed’);array_walk($stuff, function(&$value) {

$value = strtoupper($value);});// ’APPLE’, ’ANISE’, ’APPLESAUCE’, ’APPLESEED’

Page 28: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Mapping

26 April 2011 Anonymous Functions in PHP 5.3 19

• Mapping performs work on each element, resultingin a new array with the values returned.

Page 29: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Mapping

26 April 2011 Anonymous Functions in PHP 5.3 19

• Mapping performs work on each element, resultingin a new array with the values returned.

$stuff = array(’apple’, ’Anise’, ’Applesauce’, ’appleseed’);$mapped = array_map(function($value) {

$value = strtoupper($value);return $value;

}, $stuff);// $stuff: array(’apple’, ’Anise’, ’Applesauce’, ’appleseed’)// $mapped: array(’APPLE’, ’ANISE’, ’APPLESAUCE’, ’APPLESEED’)

Page 30: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Reducing

26 April 2011 Anonymous Functions in PHP 5.3 20

• “Combine” elements and return a value or data set.

Page 31: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Reducing

26 April 2011 Anonymous Functions in PHP 5.3 20

• “Combine” elements and return a value or data set.• Return value is passed as first argument of next call.

Page 32: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Reducing

26 April 2011 Anonymous Functions in PHP 5.3 20

• “Combine” elements and return a value or data set.• Return value is passed as first argument of next call.• Seed the return value by passing a third argument to

array_reduce().

$stuff = array(’apple’, ’Anise’, ’Applesauce’, ’appleseed’);$reduce = array_reduce($stuff, function($count, $input) {

$count += substr_count($input, ’a’);return $count;

}, 0);// $stuff: array(’apple’, ’Anise’, ’Applesauce’, ’appleseed’)// $reduce: 3

Page 33: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Filtering

26 April 2011 Anonymous Functions in PHP 5.3 21

• Return only the elements that evaluate to true.

Page 34: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Filtering

26 April 2011 Anonymous Functions in PHP 5.3 21

• Return only the elements that evaluate to true.• Often, this is a form of mapping, and used to trim a

dataset to only those of interest prior to reducing.

$stuff = array(’apple’, ’Anise’, ’Applesauce’, ’appleseed’);$reduce = array_reduce($stuff, function($count, $input) {

$count += substr_count($input, ’a’);return $count;

}, 0);// $stuff: array(’apple’, ’Anise’, ’Applesauce’, ’appleseed’)// $reduce: 3

Page 35: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

String operations

26 April 2011 Anonymous Functions in PHP 5.3 22

• Regular expressions (preg_replace_callback)

Page 36: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

String operations

26 April 2011 Anonymous Functions in PHP 5.3 22

• Regular expressions (preg_replace_callback)• Currying arguments

Page 37: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

preg_replace_callback()

26 April 2011 Anonymous Functions in PHP 5.3 23

• Allows you to transform captured matches.

$string = "Today’s date next month is " . date(’Y-m-d’);$fixed = preg_replace_callback(’/(\d{4}-\d{2}-\d{2})/’,function($matches) {

$date = new DateTime($matches[1]);$date->add(new DateInterval(’P1M’));return $date->format(’Y-m-d’);

}, $string);// "Today’s date next month is 2011-05-26"

Page 38: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Currying arguments

26 April 2011 Anonymous Functions in PHP 5.3 24

• In some cases, you may want to provide defaultarguments:

Page 39: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Currying arguments

26 April 2011 Anonymous Functions in PHP 5.3 24

• In some cases, you may want to provide defaultarguments:

• To reduce the number of arguments needed.

Page 40: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Currying arguments

26 April 2011 Anonymous Functions in PHP 5.3 24

• In some cases, you may want to provide defaultarguments:

• To reduce the number of arguments needed.• To supply values for optional arguments.

Page 41: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Currying arguments

26 April 2011 Anonymous Functions in PHP 5.3 24

• In some cases, you may want to provide defaultarguments:

• To reduce the number of arguments needed.• To supply values for optional arguments.• To provide a unified signature for callbacks.

Page 42: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Currying arguments

26 April 2011 Anonymous Functions in PHP 5.3 24

• In some cases, you may want to provide defaultarguments:

• To reduce the number of arguments needed.• To supply values for optional arguments.• To provide a unified signature for callbacks.

$hs = function ($value) {return htmlspecialchars($value, ENT_QUOTES, "UTF-8", false);

};$filtered = $hs("<span>Matthew Weier O’Phinney</span>");// "&lt;span&gt;Matthew Weier O&#039;Phinney&lt;/span&gt;"

Page 43: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Gotchas

Page 44: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

References

26 April 2011 Anonymous Functions in PHP 5.3 26

• Variables passed to callbacks, either as argumentsor imports, are not passed by reference.

Page 45: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

References

26 April 2011 Anonymous Functions in PHP 5.3 26

• Variables passed to callbacks, either as argumentsor imports, are not passed by reference.

• Use objects, or

Page 46: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

References

26 April 2011 Anonymous Functions in PHP 5.3 26

• Variables passed to callbacks, either as argumentsor imports, are not passed by reference.

• Use objects, or• Pass by reference

Page 47: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

References

26 April 2011 Anonymous Functions in PHP 5.3 26

• Variables passed to callbacks, either as argumentsor imports, are not passed by reference.

• Use objects, or• Pass by reference

$count = 0;$counter = function (&$value) use (&$count) {

if (is_int($value)) {$count += $value;$value = 0;

}};$stuff = array(’foo’, 1, 3, ’bar’);array_walk($stuff, $counter);// $stuff: array(’foo’, 0, 0, ’bar’)// $count: 4

Page 48: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Mixing with other callables

26 April 2011 Anonymous Functions in PHP 5.3 27

Problems and considerations:

• Closure is an “implementation detail”; typehintingon it excludes other callback types.

Page 49: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Mixing with other callables

26 April 2011 Anonymous Functions in PHP 5.3 27

Problems and considerations:

• Closure is an “implementation detail”; typehintingon it excludes other callback types.

• is_callable() tells us only that it can be called,not how.

Page 50: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Mixing with other callables

26 April 2011 Anonymous Functions in PHP 5.3 27

Problems and considerations:

• Closure is an “implementation detail”; typehintingon it excludes other callback types.

• is_callable() tells us only that it can be called,not how.

• is_callable() && is_object() tells us wehave a functor, but omits other callback types.

Page 51: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Mixing with other callables

26 April 2011 Anonymous Functions in PHP 5.3 28

Three ways to call (1/3):

• $o($arg1, $arg2)

Page 52: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Mixing with other callables

26 April 2011 Anonymous Functions in PHP 5.3 28

Three ways to call (1/3):

• $o($arg1, $arg2)

• Benefits: speed.

Page 53: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Mixing with other callables

26 April 2011 Anonymous Functions in PHP 5.3 28

Three ways to call (1/3):

• $o($arg1, $arg2)

• Benefits: speed.• Problems: won’t work unless we have a functor,

closure, or static method call.

Page 54: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Mixing with other callables

26 April 2011 Anonymous Functions in PHP 5.3 29

Three ways to call (2/3):

• call_user_func($o, $arg1, $arg2)

Page 55: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Mixing with other callables

26 April 2011 Anonymous Functions in PHP 5.3 29

Three ways to call (2/3):

• call_user_func($o, $arg1, $arg2)

• Benefits: speed, works with all callables.

Page 56: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Mixing with other callables

26 April 2011 Anonymous Functions in PHP 5.3 29

Three ways to call (2/3):

• call_user_func($o, $arg1, $arg2)

• Benefits: speed, works with all callables.• Problems: if number of arguments are unknown

until runtime, this gets difficult.

Page 57: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Mixing with other callables

26 April 2011 Anonymous Functions in PHP 5.3 30

Three ways to call (3/3):

• call_user_func_array($o, $argv)

Page 58: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Mixing with other callables

26 April 2011 Anonymous Functions in PHP 5.3 30

Three ways to call (3/3):

• call_user_func_array($o, $argv)

• Benefits: works with all callables., works withvariable argument counts.

Page 59: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Mixing with other callables

26 April 2011 Anonymous Functions in PHP 5.3 30

Three ways to call (3/3):

• call_user_func_array($o, $argv)

• Benefits: works with all callables., works withvariable argument counts.

• Problems: speed (takes up to 6x longer toexecute than straight call).

Page 60: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

You cannot import $this

26 April 2011 Anonymous Functions in PHP 5.3 31

• Creative developers will want to use closures tomonkey-patch objects.

Page 61: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

You cannot import $this

26 April 2011 Anonymous Functions in PHP 5.3 31

• Creative developers will want to use closures tomonkey-patch objects.

• You can. You just can’t use $this, which meansyou’re limited to public methods.

Page 62: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

You cannot import $this

26 April 2011 Anonymous Functions in PHP 5.3 31

• Creative developers will want to use closures tomonkey-patch objects.

• You can. You just can’t use $this, which meansyou’re limited to public methods.

• Also, you can’t auto-dereference closures assignedto properties.

Page 63: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Example: Monkey-Patching

26 April 2011 Anonymous Functions in PHP 5.3 32

class Foo{

public function __construct(){

$self = $this;$this->bar = function () use ($self) {

return get_object_vars($self);};

}

public function addMethod($name, Closure $c){

$this->$name = $c;}

public function __call($method, $args){

if (property_exists($this, $method) &&is_callable($this->$method)) {

return call_user_func_array($this->$method, $args);}

}}

Page 64: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Serialization

26 April 2011 Anonymous Functions in PHP 5.3 33

• You can’t serialize anonymous functions.

Page 65: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Some Use Cases

Page 66: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Aspect Oriented Programming

26 April 2011 Anonymous Functions in PHP 5.3 35

• Code defines “aspects,” or code that cuts acrossboundaries of many components.

Page 67: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Aspect Oriented Programming

26 April 2011 Anonymous Functions in PHP 5.3 35

• Code defines “aspects,” or code that cuts acrossboundaries of many components.

• AOP formalizes a way to join aspects to other code.

Page 68: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Aspect Oriented Programming

26 April 2011 Anonymous Functions in PHP 5.3 35

• Code defines “aspects,” or code that cuts acrossboundaries of many components.

• AOP formalizes a way to join aspects to other code.• Often, you will need to curry arguments in order to

maintain signatures.

Page 69: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Event Management example

26 April 2011 Anonymous Functions in PHP 5.3 36

$front->events()->attach(’dispatch.router.post’, function($e) use($cache) {

$request = $e->getParam(’request’);if (!$request instanceof Zend\Http\Request || !$request->isGet())

{return;

}

$metadata = json_encode($request->getMetadata());$key = hash(’md5’, $metadata);$backend = $cache->getCache(’default’);if (false !== ($content = $backend->load($key))) {

$response = $e->getParam(’response’);$response->setContent($content);return $response;

}return;

});

Page 70: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

That’s all, folks!

Page 71: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

References

26 April 2011 Anonymous Functions in PHP 5.3 38

• PHP Manual:http://php.net/functions.anonymous

Page 72: Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney

Thank You!