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

they can bite! – how (not) to use accessors ... Eloquent mutators & accessors are handy feature that can simplify your high level code and hide some data-related logic in the model. Howev...
Revisionable – a quick example A short reminder about my revisionable package (compatible with L4 & L5+) and quick example of how you can use it: 1. Controller: 2....
Laravel – Custom pivot model in Eloquent Sometimes you may wish to use custom pivot model when working with many-to-many relationships in Eloquent, in order to add some behaviour on top o...
Laravel – querying any level far relations w... Eloquent provides one Relation type for far related tables - hasManyThrough. However it works only with with cascade of hasOne/hasMany relations a...