Created
October 3, 2021 09:37
-
-
Save Baptouuuu/82d3e1d996eba610d6c5dd4f6bbac0a8 to your computer and use it in GitHub Desktop.
Objects are parameterised functions
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 | |
| declare(strict_types=1); | |
| $constructor = function(string $name) { | |
| $properties = ['name' => $name]; | |
| return function(string $method) use (&$properties) { | |
| return match($method) { | |
| 'say' => fn() => print('hello '.$properties['name']."\n"), | |
| 'rename' => function(string $name) use (&$properties): void { | |
| $properties['name'] = $name; | |
| }, | |
| }; | |
| }; | |
| }; | |
| final class User | |
| { | |
| public function __construct(private string $name) | |
| { | |
| } | |
| public function say(): void | |
| { | |
| print('hello '.$this->name."\n"); | |
| } | |
| public function rename(string $name): void | |
| { | |
| $this->name = $name; | |
| } | |
| } | |
| $user = $constructor('John'); | |
| $user('say')(); | |
| $user('rename')('Jane'); | |
| $user('say')(); | |
| $user = new User('John'); | |
| $user->say(); | |
| $user->rename('Jane'); | |
| $user->say(); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Will output: