Last active
October 15, 2022 15:10
-
-
Save tbreuss/5e5ca3b9def172e296cdf3e948e741fa to your computer and use it in GitHub Desktop.
Different PHP Callbacks
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 | |
// Examples for different uses of PHP callbacks | |
output(callback(function() { return 'anonymous function'; })); | |
output(callback('func')); | |
output(callback(new InvokableClass())); | |
output(callback([new NormalClass(), 'test'])); | |
output(callback('StaticClass::staticMethod')); | |
output(callback([StaticClass::class, 'staticMethod'])); | |
output(callback(['StaticClass', 'staticMethod'])); | |
output(callback(InvokableClass::class)); | |
output(callback(StringableClass::class)); | |
// This prints out: | |
// anonymous function | |
// func | |
// InvokableClassInvokableClass::__invoke | |
// NormalClassNormalClass::test | |
// StaticClassStaticClass::staticMethod | |
// StaticClassStaticClass::staticMethod | |
// StaticClassStaticClass::staticMethod | |
// InvokableClassInvokableClass::__invoke | |
// StringableClassStringableClass::__toString | |
function callback($callable): string | |
{ | |
if (is_string($callable)) { | |
if (function_exists($callable)) { | |
return $callable(); | |
} | |
if (class_exists($callable)) { | |
$obj = (new $callable); | |
if (is_callable($obj)) { | |
return $obj(); | |
} | |
if (method_exists($obj, '__toString')) { | |
return $obj; | |
} | |
} | |
} | |
return $callable(); | |
} | |
function func() | |
{ | |
return __FUNCTION__; | |
} | |
class StaticClass | |
{ | |
public static function staticMethod() | |
{ | |
return __CLASS__ . __METHOD__; | |
} | |
} | |
class NormalClass | |
{ | |
public function test() | |
{ | |
return __CLASS__ . __METHOD__; | |
} | |
} | |
class InvokableClass | |
{ | |
public function __invoke() | |
{ | |
return __CLASS__ . __METHOD__; | |
} | |
} | |
class StringableClass | |
{ | |
public function __toString() | |
{ | |
return __CLASS__ . __METHOD__; | |
} | |
} | |
function output(string $what): void | |
{ | |
echo $what . '<br>'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment