Last active
July 21, 2022 20:54
-
-
Save RodrigoDornelles/9fb293f2b484281521de848bc2c12467 to your computer and use it in GitHub Desktop.
from scratch object-oriented recreation based on the functional paradigm.
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 | |
$class = call_user_func(function () { | |
$objects = []; | |
return function() use (&$objects) { | |
return (object) [ | |
'instanceof' => function($object) use (&$objects) { | |
return in_array($object, $objects); | |
}, | |
'construtor' => function() use (&$objects) { | |
$private = (object) [ | |
'name' => '', | |
'set_name' => fn ($self, $new_name) => $self->name = $new_name, | |
'hello' => fn ($self) => print("hello {$self->name}!\n"), | |
]; | |
$public = fn () => (object) [ | |
'set_name' => fn($new_name) => call_user_func($private->set_name, $private, $new_name), | |
'hello' => fn() => call_user_func($private->hello, $private), | |
]; | |
$objects[] = $public; | |
return $public; | |
} | |
]; | |
}; | |
}); | |
$my_obj = call_user_func(call_user_func($class)->construtor); | |
call_user_func(call_user_func($my_obj)->set_name, 'Dornelles'); | |
$my_obj2 = call_user_func(call_user_func($class)->construtor); | |
call_user_func(call_user_func($my_obj2)->set_name, 'Cristian'); | |
call_user_func(call_user_func($my_obj)->hello); | |
call_user_func(call_user_func($my_obj2)->hello); | |
var_dump(call_user_func(call_user_func($class)->instanceof, $my_obj)); | |
var_dump(call_user_func(call_user_func($class)->instanceof, $my_obj2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
alternative syntax
Output