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:

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

Related Post

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...
Tinker like a boss – WTF?! This is part of the series tinker like a boss (in psysh) tinker... what? includes casters (presenters) aliases http (and other) helpers ...
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....