Using Anonymous Functions in Laravel 3

I was using Laravel, the PHP framework for the first time for one of my web applications here and it (Laravel) is really awesome. Laravel uses one of the new (since PHP 5.3) feature that is anonymous function or closure (also known as lambada function) in many places including the Validator class and it lets the developer to register  custom validation rule something like

In one of my controller classes I was using this to register my custom rule to validate post code and it was working fine on my local environment but suddenly I found that it’s not working on live server and after some searching on the net I found that For PHP 5.3, $this support for anonymous functions (Closures) was removed and I was using $this in the anonymous function. It was working on my local environment because I had PHP 5.4 installed but on the live server it was PHP 5.3.  The function I was using was something like

Above code was throwing following error

Unhandled Exception
Using $this when not in object context

Then in my controller class I’ve changed it to following and the problem solved.

The problem was that you can’t use keyword $this in an anonymous function unless you are using PHP 5.4. In the above code snippet, I’ve just passed the $_location array to the anonymous function as reference using use keyword and used the private array in the function without any problem. Hope this will help somebody. Finally I would like to say that Laravel is really a grate framework and I’m in love with it. Anyone who didn’t try it yet,  should try it now.

Latest Blog


PHP – 8.0 Match Expression

In PHP 8.0 there is a new feature or I should say a new language construct (keyword) going to be introduced,  which has been implemented depending […]


New Union Type in PHP – 8

A new RFC has been finished voting and accepted for PHP – 8. That is “Union Types”, which is an extension of PHP’s type system. […]