Skip to content

Instantly share code, notes, and snippets.

@SammyK
Created August 25, 2014 18:09
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 SammyK/2e2fd66516dfc025887b to your computer and use it in GitHub Desktop.
Save SammyK/2e2fd66516dfc025887b to your computer and use it in GitHub Desktop.
Possible PHP RFC? Call function based on function header

I don't know enough about how programming languages work to even know what this is called. But when working on an event emitter, I thought it'd be cool if PHP would be able to support this:

class FooClass {
  function bam() { echo 'BAM!'; }
}

function foo(array $bar = []) {
  print_r($bar);
}

function foo(array $bar = [], $baz) {
  echo $baz . ' likes ' . $bar[0];
}

function foo(FooClass $bar) {
  $bar->bam();
}

$data = ['foo','bar']
foo($data);
// prints results from `print_r($data);`

foo($data, 'david');
// david likes foo

$fooObject = new FooClass();
foo($fooObject);
// BAM!

And I'm trying to figure out how it'd work with closures.

$myFunc = function (FooClass $foo) {
};
$myFunc = function (array $foo) {
};

This would make, for example, coding a Listener() super easy to write:

$listener = new Listener();

$listener->on(function (SuccessEvent $foo) {
  // . . .
});

$listener->on(function (ErrorEvent $foo) {
  // . . .
});

$listener->on(function (BarEvent $foo) {
  // . . .
});

Or is all this just a bad practice idea? Thoughts? :)

@SammyK
Copy link
Author

SammyK commented Aug 25, 2014

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