Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP PHP Functions Function Returns and More PHP Closures

Variable Functions vs. PHP Closures

What's the difference between assigning a function to a variable vs. these anonymous functions, or PHP Closures? I get that you can use outside variables using the 'use' command with Closures .... is that the only difference? Why would you use one instead of the other?

2 Answers

Andrew Shook
Andrew Shook
31,709 Points

What you are really asking here is what is the difference between a Lambda (variable function) and a closure in PHP. If i remember correctly, the benefit of a lambda is that it exists only as long as the variable it is assigned to has a reference. So the way PHP manages memory is by reference counting. Essentially, the PHP engine reads all the files it needs in order to execute the program, and while doing so it finds all the variables used and keeps a tally of how many times they are used( reference count). While the script is being executed each time the variable is used it subtracts one from the reference count. Once the reference count hits zero, the variable is deleted (more or less). Normally, a function is loaded into memory and stays there for the entire execution of the script. However, a lambda can be deleted from memory once the reference count of its variable hits zero.

A closure on the other hand is an anonymous function that encapsulates a part of the global scope at the time it is created. In other words, you can pass a variable to a closure using the "use" keyword and that variable's value will be the same as it was when the closure was created regardless of what happen's outside the closure. So:

<?php
    $i = 0;
    // Increase counter within the scope
    // of the function
    $closure = function () use ($i){ return $i++; };
    // Run the function
    echo $closure();// Returns 1
    // The global count hasn't changed
    echo $i; // Returns 0

I copy pasted your code, the output was "00", not "10" - any idea why?

I changed it to return $i + 1; and it works. Or you can do $i++; return $i;

Andrew Shook
Andrew Shook
31,709 Points

You actually need to do ++$i not $I++. Sorry, that was a typo on my part.

Thanks!