Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- define('TYPEHINT_PCRE', '/^Argument (\d)+ passed to (?:(\w+)::)?(\w+)\(\) must be an instance of (\w+), (\w+) given/');
- class Typehint
- {
- private static $Typehints = array(
- 'Bool' => 'is_bool',
- 'Int' => 'is_int',
- 'Float' => 'is_float',
- 'String' => 'is_string',
- 'Resource' => 'is_resource'
- );
- private function __construct() {}
- public static function initializeHandler()
- {
- set_error_handler('Typehint::handleTypehint');
- return true;
- }
- private static function getTypehintedArgument($ThBackTrace, $ThFunction, $ThArgIndex, &$ThArgValue)
- {
- foreach ($ThBackTrace as $ThTrace)
- {
- // Match the function; Note we could do more defensive error checking.
- if (isset($ThTrace['function']) && $ThTrace['function'] == $ThFunction) {
- $ThArgValue = $ThTrace['args'][$ThArgIndex - 1];
- return true;
- }
- }
- return false;
- }
- public static function handleTypehint($ErrLevel, $ErrMessage)
- {
- if ($ErrLevel == E_RECOVERABLE_ERROR) {
- if (preg_match(TYPEHINT_PCRE, $ErrMessage, $ErrMatches)) {
- list($ErrMatch, $ThArgIndex, $ThClass, $ThFunction, $ThHint, $ThType) = $ErrMatches;
- if (isset(self::$Typehints[$ThHint])) {
- $ThBacktrace = debug_backtrace();
- $ThArgValue = NULL;
- if (self::getTypehintedArgument($ThBacktrace, $ThFunction, $ThArgIndex, $ThArgValue)) {
- if (call_user_func(self::$Typehints[$ThHint], $ThArgValue)) {
- return true;
- }
- }
- }
- }
- }
- return false;
- }
- }
- Typehint::initializeHandler();
- ?>
- An are some examples of the class in use:
- <?php
- function teststring(String $string) { echo $string; }
- function testinteger(Int $integer) { echo $integer; }
- function testfloat(Float $float) { echo $float; }
- // This will work for class methods as well.
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement