Skip to content

Instantly share code, notes, and snippets.

@Baptouuuu
Created October 3, 2021 09:37
Show Gist options
  • Select an option

  • Save Baptouuuu/82d3e1d996eba610d6c5dd4f6bbac0a8 to your computer and use it in GitHub Desktop.

Select an option

Save Baptouuuu/82d3e1d996eba610d6c5dd4f6bbac0a8 to your computer and use it in GitHub Desktop.
Objects are parameterised functions
<?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();
@Baptouuuu
Copy link
Copy Markdown
Author

Will output:

hello John
hello Jane
hello John
hello Jane

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment