Skip to content

Instantly share code, notes, and snippets.

@woprrr
Created September 19, 2019 09:48
Show Gist options
  • Save woprrr/f8b975a2406c11ed4b5b62e5a47e9895 to your computer and use it in GitHub Desktop.
Save woprrr/f8b975a2406c11ed4b5b62e5a47e9895 to your computer and use it in GitHub Desktop.
Closure in PHP 7.1 examples
<?php
function writeln($line_in) {
echo $line_in." \n";
}
class Test {
public $number;
function __construct(int $number)
{
$this->number = $number;
}
public function getNumber(): int
{
return $this->number;
}
public function multiplyStatically(): int
{
return $this->number * 2;
}
public function multiplyWithParams(int $multiplicator): int
{
return $this->number * $multiplicator;
}
}
$test = new Test(2);
writeln('START');
writeln('');
writeln('Context 1 - Raw number');
writeln($test->getNumber());
writeln('');
$cl1 = \Closure::fromCallable([$test, 'multiplyStatically']);
writeln('Context 2 - static multiply number');
writeln($cl1->call($test));
writeln('');
$cl2 = \Closure::fromCallable([$test, 'multiplyWithParams']);
writeln('Context 3 - Multiply number by multiplicator');
writeln($cl2->call($test, '9'));
writeln('');
writeln('END');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment