0

这失败了(编造的代码):

namespace Season\Summer;

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

和:

"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."

似乎命名空间正在导致 PHP 的内置类型提示出现问题,因为我认为它正在检查参数$month是标量类型stringSeason\Summer\而不是string(我可能错了)的全局定义。

我怎样才能解决这个问题?解决办法是什么?给我们is_*()里面的函数?

4

2 回答 2

5

PHP 不支持string类型提示。如果您需要 $month 作为字符串,请从方法参数中删除字符串,将其强制转换或使用以下命令检查它是否为字符串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.");
        }
    }
}

文档可以在这里找到

于 2013-07-12T22:25:55.207 回答
-2

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.

于 2015-02-23T23:54:26.453 回答