closure

Anonymous functions, in php known as Closures, come in handy very often. One application in particular is very useful – extending classes, thanks to the capability to bind the closure to an instance and class scope.

However, binding to instance may prove a bit tricky, so let’s go through it together.

Let’s start with a simple example:

Unfortunately above code will show following error Warning: Cannot bind an instance to a static closure.

While it’s rather unlikely that you use it in a static context like above, but chances are you do something like this:

OK, it’s not very sophisticated example, but you get the idea already (you can find real use-case in eg. Laravel Metable). Here, the closure is created again in a static context and it makes perfect sense in this case, but it means we’ll  get the same error as soon as macro is called: $foo->fullName().

Important thing to remember though is that php doesn’t care about the context, in which we invoke the process but only where the closure is created. That being said, a workaround for this is as simple as having additional class, providing instance context:

then we can rewrite our boot method:

and make it work!

 

Having a bindTo method that in fact can’t do its job is a huge drawback in php 5.x, but we can easily work around the problem.

Wait, did I say php5? Right, because awaited and upcoming PHP7 fixes it. Speaking of, worth reading walkthrough to the Seven:  oreilly.com/web-platform/free/files/upgrading-to-php-seven.pdf

It's only fair to share...Tweet about this on TwitterShare on RedditPin on PinterestShare on FacebookShare on Google+

Related Post

20 Eloquent tricks – more Recently I stumbled upon interesting article by Povilas Korop on laravel-news 20 eloquent tips and tricks. First of all thanks for sharing your knowle...
A story about Laravel Resources Leo is a brilliant developer. He turns every idea into code in no time. He's prepared for any task thrown at him and dives into coding straight away, ...
How to add custom casters in Laravel tinker I made a series about psysh and Laravel's tinker - powerful REPL where you can play with your whole application. ICYMI check it out here: tinker li...
Too much M4g1c will kill you (or at least bite you... So, as you know, I'm a big fan of Laravel, in particular Eloquent is my favourite. The beauty and value of both is a lot of conventions and magic...