Skip to content

Instantly share code, notes, and snippets.

@cspray
Last active April 1, 2022 21:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cspray/ec53ad92baa7d9829e21f7111d4eb919 to your computer and use it in GitHub Desktop.
Save cspray/ec53ad92baa7d9829e21f7111d4eb919 to your computer and use it in GitHub Desktop.
A spike for having CallableInterfaces in PHP
<?php
// In PHP internals, maybe this is an abstract class instead?
// Maybe an attribute?
#[Attribute]
class FunctionalInterface {}
#[FunctionalInterface]
interface MyAction {
public function invoke(string $foo, int $bar) : bool;
}
class ObjectAction implements MyAction {
public function invoke(string $foo, int $bar) : bool {
echoo $foo, $bar;
return true;
}
}
function doIt(MyAction $action) {
$action->invoke('foo', 42);
}
$goodFunc = function(string $a, int $b) : bool {
echo $b, $a;
return true;
};
$badFunc = function() {};
doIt(new ObjectAction()); // 'foo', 42
doIt($goodFunc); // 42, 'foo'
doIt($badFunc); // exception, wrong method signature
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment