PHP返回类型

Ger*_*rep 11 php return return-type

是否可以像这样定义返回类型?

public static function bool Test($value)
{
      return $value; //this value will be bool
}
Run Code Online (Sandbox Code Playgroud)

dom*_*son 33

由于此问题仍出现在Google搜索结果中,因此这是一个最新的答案:

PHP 7实际上为这个RFC引入了函数/方法的正确返回类型.

以下是上面链接的手册中的示例:

function sum($a, $b): float {
    return $a + $b;
}
Run Code Online (Sandbox Code Playgroud)

或者,用更一般的表示法:

function function_name(): return_type {
    // some code
    return $var // Has to be of type `return_type`
}
Run Code Online (Sandbox Code Playgroud)

如果返回的变量或值与返回类型不匹配,PHP将隐式将其转换为该类型.或者,您可以启用文件的严格键入declare(strict_types=1);,在这种情况下,类型不匹配将导致TypeError异常.

很简单.但是,请记住,您需要确保PHP 7在您的开发和生产服务器上都可用.

  • @PetruLebada 最近的一项功能允许将返回类型标记为允许 `null` 作为值,请参阅 [关于 Nullable 类型的 PHP 文档](http://php.net/manual/en/migration71.new-features.php) . (2认同)

Jef*_*ker 16

在方法/函数级别无法显式定义返回类型.按照规定,您可以在回报中进行投射,例如......

return (bool)$value;
Run Code Online (Sandbox Code Playgroud)

或者,您可以在phpDoc语法中添加注释,并且许多IDE将从类型完成角度提取类型.

/**
 * example of basic @return usage
 * @return myObject
 */
function fred()
{
    return new myObject();
}
Run Code Online (Sandbox Code Playgroud)


Adi*_*dil 6

PHP 7 中添加的返回类型;)

https://wiki.php.net/rfc/return_types


Dhr*_*hak 5

根据此页面:http: //php.net/manual/en/language.types.type-juggling.php

你可以试试,

return (boolean) $value;
Run Code Online (Sandbox Code Playgroud)

现在PHP提供了PHP 7的返回类型声明.我已经解释了如何在PHP中使用返回类型