Question

This fails (made up code):

namespace Season\Summer;

class Summer
{
    public static function days(string $month)
    {
        // ...
    }
}

With:

"Argument 1 passed to Season\\Summer\\Summer::days() must be an instance of string, string given, called in /path/to/Seasons/Summer/Summer.php on line 5."

It seems namespacing is causing issue with PHP's inbuilt type hinting as I think it's checking the parameter $month is of scalar type string class Season\Summer\ rather than the global definition of string (I may be wrong).

How can I get around this? What is the solution? To us is_*() inside the function?

Was it helpful?

Solution

PHP doesn't support string as type hinting. If you need $month as a string, strip the string from the method parameter, cast it or check it is a string using is_string():

namespace Season\Summer;

class Summer
{
    public static function days($month)
    {
        $month = (string) $month;
        // or
        if (! is_string($month)) {
            throw new Exception("Argument $month is not a string.");
        }
    }
}

Documentation can be found here.

OTHER TIPS

I have registered an own errorhandler looking like that:

namespace framework;        
    class Error {

        static $arHintsShorts = array('integer'=>'int', 'double'=>'float');

    public static function execHandler( $iErrno, $sErrstr, $sErrfile, $iErrline ) {


    if ( preg_match('/Argument (\d)+ passed to (.+) must be an instance of (?<hint>.+), (?<given>.+) given/i',
                                $sErrstr, $arMatches ) )
                {
                    $sGiven = $arMatches[ 'given' ] ;
                    $arHints =  explode( '\\', $arMatches[ 'hint' ] );
                    $sHint  = strtolower( end($arHints) );

                    if (isset(self::$arHintsShorts[$sGiven])) {
                        $sGiven = self::$arHintsShorts[$sGiven];
                    }

                    if ( $sHint == strtolower($sGiven) || $sHint == 'mixed' || ($sHint == 'float' && $sGiven == 'int')) {
                        return TRUE;
                    } else {
                        if (self::$oLog != null) {
                            self::$oLog->error($sErrstr . '(' . $iErrno . ', ' . $sErrfile . ', ' . $iErrline . ')');
                        }
                        throw new \UnexpectedValueException($sErrstr, $iErrno);
                    }
                }

        }
    }

set_error_handler(array('framework\error', 'execHandler'), error_reporting());

It handles all primitive types although in namespaced classes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top