note 102827 deleted from language.oop5.typehinting by danbrown
| From: | danbrown@php.net | Date: | Wed, 09 Mar 2011 01:09:16 +0000 |
| Subject: | note 102827 deleted from language.oop5.typehinting by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-177675@lists.php.net to get a copy of this message | ||
Note Submitter: brett at nobistech dot net
----
The following code posted has a problem when in E_STRICT mode.
------------------------------------------------------------------
For PHP 5.3 version and namespaces support.
<?php
function phpErrorHandler( $code, $message, $file, $line ) {
if ( error_reporting() & $code ) {
if ( $code == E_RECOVERABLE_ERROR ) { // Scalar Type-Hinting patch.
$regexp = '/^Argument (\d)+ passed to (.+) must be an instance of
(?<hint>.+), (?<given>.+) given/i' ;
if ( preg_match( $regexp, $message, $match ) ) {
$given = $match[ 'given' ] ;
$hint = end( explode( '\\', $match[ 'hint' ] ) ) ; //
namespaces support.
if ( $hint == $given ) return true ;
}
}
return false ;
}
}
set_error_handler( 'phpErrorHandler' ) ;
/************************************/
function typeHintTest( integer $arg1 ) {
print_r( $arg1 ) ;
}
typeHintTest( true ) ; // Error throw because not integer type.
?>
-------------------------------------------------------------------
I changed it to the following, which ensures that $exploded (we had directly passed it to end
before) get's passed as a variable, by reference, and does not throw an error any longer.
function phpErrorHandler($code, $message, $file, $line )
{
/**
* PHP is dumb and doesn't allow scalar type-hinting by default, even with PHP 5.3.
*
* This is a workaround.
*/
if ( error_reporting() & $code ) {
if ( $code == E_RECOVERABLE_ERROR ) { // Scalar Type-Hinting patch.
$regexp = '/^Argument (\d)+ passed to (.+) must be an instance of
(?<hint>.+), (?<given>.+) given/i' ;
if ( preg_match( $regexp, $message, $match ) ) {
$given = $match[ 'given' ] ;
$exploded = explode( '\\', $match[ 'hint' ] );
$hint = end( $exploded ) ; // namespaces support.
if ( $hint == $given ) return true ;
}
}
return false ;
}
}
set_error_handler( 'phpErrorHandler' ) ;