Fork me on GitHub
/ Sweet home / Blog / Archives / PHP5 et type hinting /

PHP5 et type hinting

Last update: 2011-03-02 02:14:37

PHP permet le "type hinting" mais uniquement pour les objets et les tableaux. Voici une bouine trouvée sur php.net pour ajouter à cette fonctionnalité les types scalaires, en attendant une hypothétique modification de PHP en ce sens :

<?php
define('md_TYPEHINT_PCRE', '/^Argument (\d)+ passed to (?:(\w+)::)?(\w+)\(\) must be an instance of (\w+), (\w+) given/');
/**
 * Adapted from a contribution of daniel.l.wood@gmail.com found at php.net
 */
class md_Hint
{
	private static $Typehints = array(
		'boolean' => 'is_bool',
		'integer' => 'is_int',
		'float' => 'is_float',
		'string' => 'is_string',
		'resrouce' => 'is_resource'
	);
	public static function initializeHandler()
	{
		set_error_handler('md_Hint::handleTypehint');
		return TRUE;
	}
	private static function getTypehintedArgument($ThBackTrace, $ThFunction, $ThArgIndex, &$ThArgValue)
	{
		foreach($ThBackTrace as $ThTrace)
		{
			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(md_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;
	}
}


<< Les suggestions Google
FirePHP >>
 

Comment this