• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Programming / Beginners Guide To PHP Closure

Beginners Guide To PHP Closure

April 20, 2014 by Rana Ahsan 6 Comments

PHP Closure

PHP started supporting closure from the 5.3.0 version, but still, many PHP programmers don’t know/make effective use of it yet. I also haven’t seen that many articles on it as well. In today’s PHP closure tutorial, I will try to cover how you can start using it easily and make your web application more robust/optimized. Before driving into real examples, assuming that you are pretty new to this term, let’s know a few related definitions first:

Anonymous Function: Anonymous function is what its title implies, a function without a name. If you have worked with JavaScript, you should already be familiar with such functions. These are pretty useful for writing short inline functions, defining callback etc. A code example of a PHP anonymous function:

$functionReference = function(){
                         echo "anonymous function called";
                    };

$functionReference();
//prints: "anonymous function called"Code language: PHP (php)


You can read more details about php anonymous function on official documentation.

Lazy Loading: Lazy loading is a common design pattern which indicates the deferring of the loading of an object until it is required. Why I used this term in this article? Our closure/anonymous function will help us achieve this feature, that’s why. You will get a more clear picture; just read on.

What is Closure:

Well, closure is nothing but an object representation of an anonymous function. It is the object-oriented way to use an anonymous function. More interestingly, the above anonymous function example we just saw returns a reference to the Closure object, not only a function reference. Thus, the PHP closure method ‘bindTo’ can be applied to this reference. The other ‘bind’ method is a static and an alternate way to get the same behaviour.

Pretty simple stuff! Right? I am not giving any examples here, as you will see them already in different use cases.

What We Can Do With Closure?

Here, I will describe two simple yet powerful features that PHP closure offers us to use:

  1. accessing private data of an object instance and
  2. lazy loading

Access Private variable using a closure:

A simple example below will show you one of the superpowers of closure, accessing the private variable of an object:

class SimpleClass {
    private $privateData = 2;
}

$simpleClosure = function() {
    return $this->privateData;
};

$resultClosure = Closure::bind($simpleClosure, new SimpleClass(), 'SimpleClass');

echo $resultClosure();Code language: PHP (php)


See? So, if we just know the variable name, it’s an awesome way to use private data without modifying the existing class. In the same way, we can add/inject new behaviour to a PHP class without modifying it as well.

Lazy Loading With PHP Closure:

As we have seen in the definition, lazy loading will help prevent any initialization until it’s used. Let’s see an example of how we can achieve this. We will define a Monolog debug logger, which will only be used in certain cases.

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$logClosure = function() {
    $log = new Logger('event');
    $log->pushHandler(new StreamHandler("logfile.log", Logger::DEBUG));
    return $log;
};

//logger will not be initialized until this point
$logger = $logClosure();Code language: PHP (php)

So, as you can see here, we can write all definitions without actual initialization using a closure. Later, when needed, use it with a simple assignment as ‘$logger = $logClosure()’.

Using External Variable inside closure:

As the closure body only be executed on demand, passing some external value/variable is a little different. You will have to use a new ‘using’ keyword for this on PHP closure function definition. Let’s see another example:

$someValue = "sample external data";
$simpleClosure = function() use($someValue) {
    return "Test accessing external value inside closure ".$someValue;
};
echo $simpleClosure();Code language: PHP (php)

What’s Next?

PHP Closure implementation is frequently used in modern applications/frameworks. So, why not you? Give it a try. Happy Coding!

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Programming Tagged With: php

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. JBWebServices says

    February 15, 2016 at 1:40 pm

    I found this article very useful. I wasn’t aware of Lazy Loading or how it effected efficiency.

    Jamie @ http://www.redoma.digital

    Reply
  2. Samuel Fullman says

    February 28, 2017 at 6:53 am

    Your first function example uses `echo` two times. You do not need to “echo $functionReference()” – you’d just need to call “$functionReference()” since the echo is already in the function

    Reply
    • Md Ali Ahsan Rana says

      May 9, 2017 at 9:14 pm

      thanks, updated

      Reply
  3. Dave says

    September 15, 2017 at 1:27 am

    How would I define a function that takes a closure as a parameter? For example, imagine if PHP’s ‘array_filter’ didn’t exist…. how would you write that function?

    Reply

Trackbacks

  1. PHP Dependency Injection With Pimple - CodeSamplez says:
    April 28, 2014 at 1:11 am

    […] you know about lazy loading with PHP closure, then you will might wonder why we need another library when we can already do it. Yes, its true, […]

    Reply
  2. this keyword inside slim framework closure – PHP says:
    December 13, 2021 at 12:08 pm

    […] https://codesamplez.com/programming/php-closure-tutorial […]

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Get Facebook C# Api Access Token
    Get Facebook C# Api Access Token
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • Utilizing Config File In C#.NET Application
    Utilizing Config File In C#.NET Application
  • Getting Started With UDP Programming in Java
    Getting Started With UDP Programming in Java
  • Generate HTTP Requests using c#
    Generate HTTP Requests using c#

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023