Created
September 19, 2019 09:48
-
-
Save woprrr/f8b975a2406c11ed4b5b62e5a47e9895 to your computer and use it in GitHub Desktop.
Closure in PHP 7.1 examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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