This article is located on outdated, archived website. Please go to the new website to continue browsing. Thank you.

Open new website

How to Bind Object Scope to a Closure and Invoke It in PHP7

Closures isn’t a popular feature in php community and it’s makes me sad, because closures is an useful option makes possible to increase you performance.

Firstly let’s explain me how closures basically works in PHP. The closure is an unnamed function is helpful as callback parameter.

So here I show this on example:

<?php
$sampleArray = ['1', '2', '3'];

$data = array_walk($sampleArray, function($data) {
	echo $data * 2, PHP_EOL;
});

We will see ‘2 4 6’ on the screen. You can make a callback predefined:

<?php
$sampleArray = ['1', '2', '3'];
function sampleCallback($data) {
	echo $data * 2, PHP_EOL;
}

$data = array_walk($sampleArray, 'sampleCallback');

In this case you will receive a same result. Clear? Let’s move forward! PHP provides us possibility to apply function. ‘Apply function’ is a really old definition, and it’s a practice trusted by the time. Actually, we can apply a function to object too. For example we can create object with protected variable and apply function-getter to this object. Firstly I will show you PHP5 way:

<?php
class TestClass {
	protected $b = 'hello world';
}

//function - getter

$getB = function() {
	return $this->b;
	//pay attention, context is undefined now!
};

$applied = $getB->bindTo(new TestClass, 'TestClass');

echo $applied();

This code will display ‘hello world’ on your screen. PHP7 provides us possibility to make these operations more readable and fast. Let’s check it work:

<?php
class TestClass {
	protected $b = 'hello world';
}

//function - getter

$getB = function() {
	return $this->b;
	//pay attention, context is undefined now!
};

echo $getB->call(new TestClass);

This also will returns ‘hello world’. Now you can apply function to an object and it’s more reasonably from theoretical point of view and, of course, more easier to use.