![](/img/trans.png)
[英]How do I use global namespace type hinting inside of a namespaced class in PHP 5.3+?
[英]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
是標量類型string
類Season\\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.