簡體   English   中英

PHP:當類是命名空間時,參數類型提示問題

[英]PHP: Issue with parameter type hinting when class is namespaced

這失敗了(編寫代碼):

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_*()函數里面is_*()嗎?

PHP不支持string作為類型提示。 如果您需要$ month作為字符串,請從method參數中刪除字符串,使用is_string()檢查它或使用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.");
        }
    }
}

文檔可以在這里找到

我已注冊了一個自己的錯誤處理程序,如下所示:

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());

它處理所有原始類型,盡管在命名空間類中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM