Quick Upload

Loading...
Flash Player 9 (or above) is needed to view slideshows. We have detected that you do not have it on your computer.To install it, go here
Post to Twitter Post to Twitter
Share on Facebook
Myspace Hi5 Friendster Xanga LiveJournal Facebook Blogger Tagged Typepad Freewebs BlackPlanet gigya icons
« Prev Comments 0 - 0 of 0 Next »
    Add a comment If you have a SlideShare account, login to comment; otherwise comment as a guest.
    • Do Introduction
    • Give reason for going through this before showing first paragraph.“as part of an investigation into the foundations of mathematics”P3: This also includes our favourite language - PHP.
    • Pause at “First-class objects”Ask question: What does this mean?Explain functions and methods as being static containers for logical blocks of code.Functions are not normally “objects” – But Lambda functions ARE.
    • Minimum 10 seconds each.4
    • Minimum 10 seconds each.5
    • 5-10 second pause.Ask who have used JavaScript/lambda functions in JavaScript – Point out that many many not have even realised they’ve used them.Talk about the next slide and how very similar the PHP syntax looks, then continue to the next slide.
    • Speak about how similar it is to JavaScript.Then speak about the syntax.Possibly add further comparisons to JavaScript.7
    • Put emphasis on the fact that these are not “Closure Functions”, but rather Lambda Functions using the Closure tool.
    • Spoke earlier that Lambda Functions must be first-class objects.We see that this becomes a problem because stack-based languages have difficulty implementing them.PHP is a stack-based language.Explain point 3 in detail.Explain the solutions.1 – This would make Lambda Functions too useless to bother with.2 – This is the best solution and the solution which most programming languages take. Lets see how...
    • Introduce next slide...I want to take the opportunity to demonstrate a lambda function used anonymously.Talk about using this example and refactoring it because $setExamplesPath isn’t going to be used again.12
    • At the end of this slide. Made a comparison to how JavaScript deals with Closure scope.13
    • Make a comparison statement about how normal functions and methods are declared.
    • Walk through example:Declare $foo,Dump $foo – Shows that it is an object with a property “lambda” which is on object of class “Closure”.Set $lambda from $foo->lambda.Destroy $fooDump $foo – Shows that $foo is destroyed - A NULL value.Print the result of $lambda as a function call.Prints “Hello World”
    • Walk through example.Overwrite the $say Lambda Function with it’s result.Explain how the life of a non referenced variable inside a function usually ends after it has returned and so that is normally the expected result.The returned value of the $say Lambda Function was actually another Lambda Function. This function imports $prefix creating a closure.By doing this, the $prefix variable is actually preserved within the scope of the closure.So when $say is again executed as a lambda function, the result is a concatenated string of $prefix and $stuffix.Resulting in “Hello World”.Introduce intermission.Eat & Drink!Resume in 15-20mins.
    • Walk through the example.Declare $foo.__construct() gets called.Fetch a lambda function from the $foo object.Print it – Displays “Bar”.Destroy the $foo object.Dump $foo – Displays NULL – It can no longer be referenced... But is it gone?__destruct() has not been called.Print the result of the $bar Lambda Function.Displays Bar! – That means that the closure has maintained the object within it’s scope, but the object is lost everywhere else.Destroy $bar.__destruct() is finally called.Print $bar – Fatal Error. Everything has been destroyed.
    • Summarize the last slide.
    • Talking about $this in the scope of a Lambda Function.
    • Note the differences between the two method calls.22
    • Explain what’s happening here.24

    PHP 5.3 Part 2 - Lambda Functions & Closures

    from melechi, 1 month ago Add as contact

    279 views | 0 comments | 0 favorites | 0 embeds (Stats)

    Desc: This is Part 2 of the series about PHP 5.3. It goes into detail regarding Lambda Functions and Closures - a great new feature in PHP 5.3.

    Embed customize close
     

    More Info

    This slideshow is Public

    Views: 279 Comments: 0 Favorites: 0 Downloads: 6

    View Details: 279 on Slideshare 0 from embeds
    Flagged as inappropriate Flag as inappropriate

    Flag as inappropriate

    Select your reason for flagging this slideshow as inappropriate.

    If needed, use the feedback form to let us know more details.

    Slideshow Transcript

    1. Slide 1: L ambda F unctions & Closures A S ydney PHP Group Presentation 2 nd October 2008 B y Timothy Chandler
    2. Slide 2: Lambda Functions – Lambda Calculus  Lambda functions originate from lambda calculus which was introduced by A lonzo Church and S tephen Cole K leene in the 1930s.  The lambda calculus can be thought of as an idealized, minimalistic programming language. It is capable of expressing any algorithm, and it is this fact that makes the model of functional programming an important one.  The lambda calculus provides the model for functional programming. Modern functional languages can be viewed as embellishments to the lambda calculus.
    3. Slide 3: Lambda Functions – Implementations  Implementing the lambda calculus on a computer involves treating \"functions\" as “first-class objects”, which raises implementation issues for stack-based programming languages. This is known as the Funarg problem – M ore on this later.  M any languages implement lambda functions. These include:  Python  C++  C# (2 different implementations – S econd one improved in C# v3.0)  JavaS cript  ...and many more...
    4. Slide 4: Lambda Functions – Implementation Examples  Python: Python Lambda Function func = lambda x: x ** s2  C++: C++ Lambda Function s std::for_each(c.begin(), c.end(), std::cout << _1 * _1 << std::endl);
    5. Slide 5: Lambda Functions – Implementation Examples  C#: C# Lambda Function //Declare a delegate signature delegate double MathDelegate(double i); //Create a delegate instance s MathDelegate lambdaFunction = delegate(double i) { return Math.Pow(i, 2); }; /* Passing ' lambdaFunction ' function variable to another method, executing, and returning the result of the function */ double Execute(MathDelegate lambdaFunction) { return lambdaFunction(100); }  C# v3.0: C# v3.0 Lambda Function //Create an delegate instance s MathDelegate lambdaFunction = i => i * i; Execute(lambdaFunction);
    6. Slide 6: Lambda Functions – Implementation Examples  JavaScript: JavaScript Lambda Function var lambdaFunction=function(x) { s return x*10; } document.write(lambdaFunction(100));
    7. Slide 7: Lambda Functions – The PHP Way  PHP 5.3: PHP 5.3 Lambda Function <?php $lambdaFunction=function($x) { s return $x*10; }; print $lambdaFunction(100); ?>  Syntax: Lambda Function Syntax s function & (parameters) use (lexical vars) { body };
    8. Slide 8: Lambda Functions – The PHP Way  The goal of PHP’s Lambda function implementation is to allow for the creation of quick throw-away functions.  Don’t confuse with “create_function()”.  These functions compile at “run-time”.  These functions DO NOT compile at “compile-time”.  Optcode caches CANNOT cache them.  Bad practice.
    9. Slide 9: Closures
    10. Slide 10: Closures – The Funarg Problem  L ambda functions MUST be first-class objects.  Funarg, meaning “ functional argument” , is a problem in computer science where a “ stack-based programming language” has difficulty implementing functions as “ first- class objects” .  The problem is when the body of a function refers to a variable from the environment that it was created but not the environment of the function call.  S tandard S olutions:  Forbid such references.  Create closures.
    11. Slide 11: Closures – The PHP Funarg Problem Solution  PHP 5.3 introduces a new keyword ‘use’.  Use this new keyword when creating a lambda function to define what variables to import into the lambda functions scope – This creates a Closure.
    12. Slide 12: Closures – The “use” Keyword  E xample: Lambda Function Closure $config=array('paths'=>array('examples'=>'c:/php/projects/examples/')); $fileArray=array('example1.php','example2.php','exampleImage.jpg'); s $setExamplesPath=function($file) use($config) { return $config['paths']['examples'].$file; }; print_r(array_map($setExamplesPath,$fileArray) );  Result: Array ( [0] => c:/php/projects/examples/example1.php [1] => c:/php/projects/examples/example2.php [2] => c:/php/projects/examples/exampleImage.jpg )
    13. Slide 13: Closures – The “use” Keyword  E xample: Lambda Function Closure – As an Anonymous Function $config=array('paths'=>array('examples'=>'c:/php/projects/examples/')); $fileArray=array('example1.php','example2.php','exampleImage.jpg'); print_r(array_map ( function($file) use($config) s { return $config['paths']['examples'].$file; }, $fileArray ));  Result: Array ( [0] => c:/php/projects/examples/example1.php [1] => c:/php/projects/examples/example2.php [2] => c:/php/projects/examples/exampleImage.jpg )
    14. Slide 14: Closures – “use” as reference or copy  V ariables passed into the “ use” block are copied in by default – This is the expected PHP behaviour.  Y ou can cause a variable to be imported by reference the same way you do when defining referenced parameters in function declarations.  The PHP 5 pass by reference for objects rule still applies.
    15. Slide 15: Closures – “use” by reference  E xample: Referenced Variable Import s  Why?  A ble to directly affect the variable from within the lambda function.  If used with a large array, can prevent massive overheads.  Memory efficient.
    16. Slide 16: Lifecycle  A lambda function can be created at any point in your application, except in class declarations.  Example: Lambda Function in Class Declaration class foo { public $lambda=function() { return 'Hello World'; }; s public function __construct() { print $this->lambda(); }  Throws Error: } new foo(); Parse error: syntax error, unexpected T_FUNCTION in D:\\Development\\www\\php5.3\\lambda\\5.php on line 4
    17. Slide 17: Lifecycle  Lambda functions can live longer than whatever created them.  Example: Lifecycle Example 1 class foo { public $lambda=null; public function __construct() { $this->lambda=function() {return 'Hello World';}; } s } $foo=new foo(); var_dump($foo); $lambda=$foo->lambda; unset($foo); var_dump($foo);  Result: print $lambda(); object(foo)#1 (1) { [\"lambda\"]=> object(Closure)#2 (0) { } } NULL Hello World
    18. Slide 18: Lifecycle  Imported variables can also live longer.  Example: Lifecycle Example 2 //Create prefix say function. $say=function($prefix) { return function($suffix) use(&$prefix) { print $prefix.$suffix; }; s }; //Create suffix say function - will loose $prefix right? $say=$say('Hello '); //Wrong! - Execute new say concatenated function. $say('World!'); //Outputs \"Hello World!\" <$prefix><$suffix>  Result: Hello World
    19. Slide 19: Lifecycle – Objects  Methods and properties used in a closure can live longer than the object.  Example: Lifecycle Example 3 class foo { public $bar=\"Bar\\r\\n\"; public function __construct(){print \"__construct()\\r\\n“;} public function __destruct(){print \"__destruct()\\r\\n“;} public function getBarLambda() { return function(){return $this->bar;}; } s } $foo=new foo(); $bar=$foo->getBarLambda(); print $bar(); unset($foo); var_dump($foo); print $bar();  Result: unset($bar); print $bar(); __construct() B ar NUL L B ar __destruct() Fatal error Function name must be a string in D:\\Development\\www\\php5.3\\lambda\\8.php on line 31
    20. Slide 20: Lifecycle – Objects  If a closure exists with a reference to an object’s method or property, that object is not completely destroyed when unset.  __destruct() is NOT called until the closure is destroyed.  The unset object CANNOT be used in this situation as it will be considered a null value by anything trying to access it outside the closure environment.
    21. Slide 21: Object Orientation  L ambda Functions are Closures because they automatically get bound to the scope of the class that they are created in.  $this is not always needed in the scope.  Removing $this can save on memory.  Y ou can block this behaviour by declaring the L ambda Function as static.
    22. Slide 22: Object Orientation  Example: Static Lambda Functions class foo { public function getLambda() { return function(){var_dump($this);}; } public function getStaticLambda() s { return static function(){var_dump($this);}; } } $foo=new foo(); $lambda=$foo->getLambda(); $staticLambda=$foo->getStaticLambda(); $lambda();  Result: $staticLambda(); object(foo)#1 (0) { } NULL
    23. Slide 23: Object Orientation  PHP 5.3 introduces a new magic method.  Invokable objects are now possible through the use of the __invoke() magic method.  E ssentially makes the object a closure.
    24. Slide 24: Object Orientation  Example: Invokable Objects class foo { public function __invoke() { s print 'Hello World'; } } $foo=new foo;  Result: $foo(); Hello World
    25. Slide 25: Questions?
    26. Slide 26: Thank you. References http://en.wikipedia.org/wiki/Lambda_calculus http://en.wikipedia.org/wiki/Closure_(computer_science) http://en.wikipedia.org/wiki/Funarg_problem http://wiki.php.net/rfc/closures