Skip to content

Instantly share code, notes, and snippets.

@RodrigoDornelles
Last active July 21, 2022 20:54
Show Gist options
  • Save RodrigoDornelles/9fb293f2b484281521de848bc2c12467 to your computer and use it in GitHub Desktop.
Save RodrigoDornelles/9fb293f2b484281521de848bc2c12467 to your computer and use it in GitHub Desktop.
from scratch object-oriented recreation based on the functional paradigm.
<?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));
@RodrigoDornelles
Copy link
Author

RodrigoDornelles commented Apr 22, 2022

alternative syntax

$my_obj = ($class()->construtor)();
($my_obj()->set_name)('Dornelles');

$my_obj2 = ($class()->construtor)();
($my_obj2()->set_name)('Cristian');

($my_obj()->hello)();
($my_obj2()->hello)();

var_dump(($class()->instanceof)($my_obj));
var_dump(($class()->instanceof)($my_obj2));

Output

hello Dornelles!
hello Cristian!
bool(true)
bool(true)

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