Skip to content

Instantly share code, notes, and snippets.

@elishaukpong
Created August 2, 2021 23:00
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 elishaukpong/a5a6f0d6ee87c605f1ee893e282d0a78 to your computer and use it in GitHub Desktop.
Save elishaukpong/a5a6f0d6ee87c605f1ee893e282d0a78 to your computer and use it in GitHub Desktop.
An example to drive home the utilisation of the reflection api
<?php
class Browser
{
public static function browse($callable)
{
$params = (new ReflectionFunction($callable))->getParameters();
$args = [];
try{
foreach($params as $param){
if(! $param->getClass()){
throw new Exception('Parameter must be type hinted');
}
if(! $param->getClass()->isSubclassOf(Browsers::class)){
throw new Exception('Type Hint must implement Browsers Contract');
}
$args[] = $param->getClass()->newInstance();
}
$callable(...$args);
}catch(Exception $e){
echo $e->getMessage();
}
}
}
interface Browsers
{
public function open();
}
Class Chrome implements Browsers
{
public function open()
{
return "chrome \n";
}
}
Class Firefox implements Browsers
{
public function open()
{
return "firefox \n";
}
}
Browser::browse(function(Firefox $browser, Chrome $chrome, Firefox $firefox){
foreach(func_get_args() as $arg){
echo $arg->open();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment