PHP 返回类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5104564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:50:09  来源:igfitidea点击:

PHP return type

phpreturnreturn-type

提问by Gerep

Is it possible to define the return type like this?

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

public static function bool Test($value)
{
      return $value; //this value will be bool
}

采纳答案by DhruvPathak

As per this page : http://php.net/manual/en/language.types.type-juggling.php

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

You can try doing,

你可以试试做,

return (boolean) $value;

Now PHP offer return type declaration from PHP 7. I have explained how to use return typein PHP

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

回答by domsson

Since this question still comes up in search engine results, here is an up-to-date answer:

由于这个问题仍然出现在搜索引擎结果中,这里是一个最新的答案:

PHP 7 actually introduced proper return types for functions / methodsas per this RFC.

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

Here is the example from the manual linked above:

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

function sum($a, $b): float {
    return $a + $b;
}

Or, in a more general notation:

或者,在更一般的符号中:

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

If the returned variable or value does not match the return type, PHP will implicitly convert it to that type. Alternatively, you can enable strict typingfor the file via declare(strict_types=1);, in which case a type mismatch will lead to a TypeError Exception.

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

Easy as that. However, remember that you need to make sure that PHP 7 is available on both, your development and production server.

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

回答by Jeff Parker

It's not possible to explicitly define the return type at the method/function level. As specified, you can cast in the return, so for example ...

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

return (bool)$value;

Alternatively, you can add a comment in phpDoc syntax, and many IDEs will pick up the type from a type completion perspective.

或者,您可以在 phpDoc 语法中添加注释,许多 IDE 会从类型完成的角度选择类型。

/**
 * example of basic @return usage
 * @return myObject
 */
function fred()
{
    return new myObject();
}

回答by Adil

Return type added in PHP 7 ;)

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

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

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

回答by Haim Evgi

do cast like

做演员喜欢

 return (bool) $value;

回答by Achilleterzo

Not at the moment in PHP 5 or below, you can define type in function sign but not in the return value. Strict declarations are in mind on PHP ver. 6 and above, but are not implemented yet.

目前在 PHP 5 或更低版本中,您可以在函数符号中定义类型,但不能在返回值中定义类型。PHP 版本考虑了严格的声明。6 及以上,但尚未实施。

Maybe with some tricks you can do this, like casting before returning the value...

也许通过一些技巧你可以做到这一点,比如在返回值之前进行转换......

回答by jmblackmer

Another thing you can do to ensure that overrides don't change the return type, is to do something like this:

为确保覆盖不会更改返回类型,您可以做的另一件事是执行以下操作:

public function Test($value)
{
      return (bool) OnTest();
}

private function OnTest($value)
{
      return $value;
}

By doing this, you can allow classes that inherit from your class to change the functionality in OnTest, but still ensure that Test returns a bool value.

通过这样做,您可以允许从您的类继承的类更改 OnTest 中的功能,但仍确保 Test 返回 bool 值。

回答by Marcus Lind

Since the release of PHP7 they have now introduced Return Type Declarationsto PHP.

自 PHP7 发布以来,他们现在向 PHP引入了返回类型声明

You define the return type by appending : typewhen you define the function:

您可以通过: type在定义函数时附加来定义返回类型:

public function foo() : array
{
    return array();
}

Default Weak Mode

默认弱模式

By default PHP uses the Weak mode. The documentation explains it in the following way:

PHP 默认使用弱模式。文档以下列方式解释它:

In the default weak mode, returned values will be coerced to the correct type if they are not already of that type

在默认的弱模式下,如果返回值不是正确的类型,它们将被强制转换为正确的类型

For example, see the following example where the function returns a string, even though the defined return type is int

例如,请参阅以下示例,其中函数返回 a string,即使定义的返回类型是int

function myInt() : int {
    return "1";
}

echo gettype(myInt());
// Output is "integer"

Strong/Strict Mode

强/严格模式

You can also tell PHP to enter strict/strong mode when handling return types by setting declare(strict_types=1). What this means is that PHP will throw a TypeErrorif a function returns the wrong type. The PHP documentation explain it in the following way:

您还可以通过设置declare(strict_types=1). 这意味着TypeError如果函数返回错误类型,PHP 将抛出 a 。PHP 文档以下列方式解释它:

In strong mode, the returned value must be of the correct type, otherwise a TypeError will be thrown.

在强模式下,返回值必须是正确的类型,否则将抛出 TypeError。

declare(strict_types=1);
function myInt() : int {
    return "1";
}

echo gettype(myInt());
// Throws an TypeError

回答by Rehmat

Since PHP 7.0, you can declare the return type like this:

从 PHP 7.0 开始,您可以像这样声明返回类型:

function returnABool(): bool {
    return false;
}

Not only common data types, you can return expected object instances as well. For example you expect a function to always return an instance of a class. This can be achieved like this:

不仅是常见的数据类型,您还可以返回预期的对象实例。例如,您希望函数始终返回类的实例。这可以像这样实现:

class Biography {
    public function name() {
        return 'John Doe';
    }
}

Now you can declare the return type for this object like this:

现在你可以像这样声明这个对象的返回类型:

function get_bio(): Biography {
    return new Biography();
}

When the function or method returns an unexpected data type, a TypeErroris thrown. Here is an example where you will encounter a TypeError.

当函数或方法返回意外的数据类型时,会抛出TypeError。这是一个您将遇到TypeError的示例。

class Biography {
    public function name() {
        return 'John Doe';
    }
}

class Bio2 {
    public function name() {
        return 'John Doe';
    }
}

function get_bio(): Biography {
    return new Bio2;
}

And an example that will not throw any TypeError:

还有一个不会抛出任何TypeError的例子:

class Biography {
    public function name() {
        return 'John Doe';
    }
}

class Bio2 {
    public function name() {
        return new Biography();
    }
}

function get_bio(): Biography {
    $bio2 = new Bio2;
    return $bio2->name();
}

More details on declaring return data types for functions and methods can be learnt from the official documentation.

关于声明函数和方法的返回数据类型的更多细节可以从官方文档中了解到。

回答by James Booker

If you know the type of the returned value will be bool, then there's no point casting it within the function.

如果您知道返回值的类型将是 bool,那么在函数中强制转换它是没有意义的。

There is no way to define the return type of a function within PHP as it is loosely-typed. You will have to do your validation within the calling function.

没有办法在 PHP 中定义函数的返回类型,因为它是松散类型的。您必须在调用函数中进行验证。