/ Sweet home / Blog / Archives / PHP5 et type hinting /

PHP5 et type hinting

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;
	}
}


Last update: 2010-09-05 07:16:06


<< Les suggestions Google
FirePHP >>
 

Comment this





Benchmark ! :-)

  1. dispatch
    time  : 0.0485
    memory: 542.06 kb
  2. cms\controllers\Index::norouteAction: find published page
    time  : 0.0051
    memory: 211.4 kb
  3. cms\controllers\Index::norouteAction: find template
    time  : 0.0001
    memory: 1.22 kb
  4. cms\controllers\Index::norouteAction: find layout
    time  : 0.0001
    memory: 1.13 kb
  5. cms\models\Page::getPublishedChildren
    time  : 0.0270
    memory: 373.37 kb
  6. cms\models\Page::getAncestors
    time  : 0.0090
    memory: 305.22 kb
  7. cms\models\Page::getParent
    time  : 0.0089
    memory: 303.63 kb
  8. cms\models\Page::getPublishedLeftSibling
    time  : 0.0038
    memory: 101.87 kb
  9. cms\models\Page::getPublishedRightSibling
    time  : 0.0040
    memory: 102.76 kb
  10. cms\models\Page::getPublishedComments
    time  : 0.0011
    memory: 28.01 kb