Created
August 2, 2021 23:00
-
-
Save elishaukpong/a5a6f0d6ee87c605f1ee893e282d0a78 to your computer and use it in GitHub Desktop.
An example to drive home the utilisation of the reflection api
This file contains 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 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