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
Validator::register('awesome', function($attribute, $value, $parameters) { return $value == 'awesome'; });
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
private $_location=array('lat'=>'', 'lng'=>''); Validator::register('validpostcode', function($attribute, $value, $parameters) { //... $json = $json->results['0']; $this->_location['lat']=$json->geometry->location->lat; $this->_location['lng']=$json->geometry->location->lng; return true; // ... });
Above code was throwing following error
Message:
Using $this when not in object context
Then in my controller class I’ve changed it to following and the problem solved.
private $_location=array('lat'=>'', 'lng'=>''); $location=&$this->_location; Validator::register('validpostcode', function($attribute, $value, $parameters) use (&$location) { //... $json = $json->results['0']; $location['lat']=$json->geometry->location->lat; $location['lng']=$json->geometry->location->lng; return true; // ... });
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.