gpt4 book ai didi

PHP 类方法返回类型

转载 作者:行者123 更新时间:2023-12-03 01:56:42 27 4
gpt4 key购买 nike

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

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

最佳答案

由于此问题仍然出现在搜索引擎结果中,因此以下是最新答案:

PHP 7 实际引入 proper return types for functions / methods根据this RFC

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

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

或者,用更通用的表示法:

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

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

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

关于PHP 类方法返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5104564/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com