是否可以编写严格类型的 PHP 代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1512293/
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
Is it possible to write strictly typed PHP code?
提问by Click Upvote
For example, is it possible to write code like this:
例如,是否可以编写这样的代码:
int $x = 6;
str $y = "hello world";
bool $z = false;
MyObject $foo = new MyObject();
And is it possible to define functions like this:
是否可以定义这样的函数:
public int function getBalance()
{
return 555; //Or any numeric value
}
采纳答案by code_burgar
Edit:This answer applies to versions of PHP 5.6 and earlier. As noted in recent answers, PHP version 7.0 and later does have some support for this
编辑:此答案适用于 PHP 5.6 及更早版本。正如最近的回答所指出的,PHP 7.0 及更高版本确实对此有一些支持
Original answer:
原答案:
No. There is only support for type hintingsince php5, but "Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported."
不。自 php5 起仅支持类型提示,但“类型提示只能是对象和数组(自 PHP 5.1 起)类型。不支持使用 int 和 string 的传统类型提示。”
In PHP 7 are implemented "Scalar Type Declarations" see the answer below.
在 PHP 7 中实现了“标量类型声明”,请参阅下面的答案。
That is as far as php currently goes, and as far as it should go if you ask me.
这是目前 php 的范围,如果你问我,它应该达到的范围。
回答by Antonín Slej?ka
In PHP 7 are implemented "Scalar Type Declarations", e.g.:
在 PHP 7 中实现了“标量类型声明”,例如:
public function getBalance(): int {
return 555;
}
You need to declare, that you will use strict types:
您需要声明,您将使用严格类型:
<?php
declare(strict_types=1);
function sum(int $a, int $b): int {
return $a + $b;
}
sum(1, 2);
?>
More information: https://wiki.php.net/rfc/scalar_type_hints_v5
回答by Alex Barrett
PHP is not strictly typed, so no. That said, it does support limited type hintingon functions - that's as close as it gets.
PHP 不是严格类型化的,所以没有。也就是说,它确实支持对函数的有限类型提示——这是尽可能接近的。
回答by Melsi
Unfortunately NO! I am at the end of a big project now that involves a lot alogorithms (graph theory, circuits etc) and I wish I hadn't choose php.
抱歉不行!我现在正在完成一个涉及很多算法(图论、电路等)的大项目,我希望我没有选择 php。
I have been using php for about 10 years, and still believe it is a good language, however one have to decide! What is bad for me, lack of strict typing might be good for someone else.
我已经使用 php 大约 10 年了,仍然相信它是一门好语言,但是必须决定!对我不好的是,缺乏严格的打字可能对其他人有好处。
In addition, I want to mention, that I often wrote extra code for supporting strict typing, just a plain example is this:
另外,我想提一下,我经常写额外的代码来支持严格类型,只是一个简单的例子是这样的:
if (is_array($r) && count($r)===0)
and the errors and hidden situations etc that were revealed are beyond explanation.
并且被揭露的错误和隐藏的情况等是无法解释的。
There were mistakes and situations that I would never been able to think/detect apriori, writing all these extra code was not enjoying but at least it will save me from silly mistakes!
有一些错误和情况我永远无法先验地思考/检测到,编写所有这些额外的代码并不享受,但至少它可以使我免于愚蠢的错误!
If I would go back, maybe I would chose php for the web part, you know getting and showing data to the user, php is just great for that, handling string, arrays, talking to the database etc etc, but for the main core, algorithms etc I would go for C++, maybe haskell.. don't know, at least something strictly typed.
如果我回去,也许我会为 Web 部件选择 php,您知道向用户获取和显示数据,php 非常适合处理字符串、数组、与数据库对话等,但对于主要核心,算法等我会选择C++,也许haskell ..不知道,至少是严格输入的东西。
回答by Calpau
Something you might try in order to simulate a poor man's strict type checking is using assert() to force the output to be of a particular type before you return it:
为了模拟穷人的严格类型检查,您可能会尝试使用 assert() 在返回之前强制输出为特定类型:
/**
* Get Balance
*
* @return int
*/
function getBalance()
{
/* blah blah blah */
$out = 555; //Or any numeric value
assert('is_int($out)');
return $out;
}
So you keep your assertions active all throughout development and testing, sort of like the checks the compiler does at compile-time.
因此,您在整个开发和测试过程中都保持断言处于活动状态,有点像编译器在编译时所做的检查。
Granted, the assert()page is keen to assert that you shouldn't use assertions to check input parameters, but rather use normal conditionals to check them.
诚然,assert()页面热衷于断言您不应使用断言来检查输入参数,而应使用正常条件来检查它们。
This answerhad what I thought was a good rule:
这个答案有一个我认为很好的规则:
The rule of thumb which is applicable across most languages (all that I vaguely know) is that an assert is used to assert that a condition is always true whereas an if is appropriate if it is conceivable that it will sometimes fail.
适用于大多数语言的经验法则(我模糊知道的所有语言)是,断言用于断言条件始终为真,而如果可以想象它有时会失败,则使用 if 是合适的。
If you're simulating strict type-checking (writing your code to viciously maintain types; not trying to validate input from the outside), then you ought to be certain what the type is unless you've made a mistake.
如果您正在模拟严格的类型检查(编写代码以恶意维护类型;而不是尝试验证来自外部的输入),那么您应该确定类型是什么,除非您犯了错误。
Update:
更新:
There's also this: http://hacklang.org/Facebook's PHP-based language with static typing.
还有这个:http: //hacklang.org/Facebook 基于 PHP 的静态类型语言。
回答by marcio
Perhaps you should try this PHP extension https://github.com/krakjoe/strict. Support for the following types is introduced:
也许你应该试试这个 PHP 扩展https://github.com/krakjoe/strict。引入了对以下类型的支持:
- string
- integer, int
- float, double
- boolean, bool
- resource
- 细绳
- 整数,整数
- 浮动,双
- 布尔值,布尔值
- 资源
回答by JavierFuentes
You could use h2tptranspilerto transpile HACK code to PHP:
您可以使用h2tp转译器将 HACK 代码转译为 PHP:
You can do this thanks to Facebook Team and HACK Language.
感谢 Facebook Team 和HACK Language,您可以做到这一点。
Visit http://hacklang.organd http://hhvm.comfor more info.
访问http://hacklang.org和http://hhvm.com了解更多信息。
If you want to code directly in Hack + HHVM environment you can also use Facebook's internal IDE Nuclide
如果你想直接在 Hack + HHVM 环境中编码你也可以使用 Facebook 的内部 IDE Nuclide
回答by dbr
Since the answer is basically "no", an alternative: A PHP "linter", which should catch some of the things a compile-time check would catch in a staticly-typed language like C. Not the same, but should prevent some sillyness
既然答案基本上是“否”,那么另一种选择:PHP“linter”,它应该捕获一些编译时检查会在像 C 这样的静态类型语言中捕获的东西。不一样,但应该防止一些愚蠢的行为
"Is there a static code analyzer [like Lint] for PHP files"lists many of these.
“是否有用于 PHP 文件的静态代码分析器 [如 Lint]”列出了其中的许多。
回答by Frank Farmer
No. That syntax will not work.
不,该语法将不起作用。
You could, theoretically, come up with a system of objects that enforced their own sort of strict typing, but it wouldn't perform and ...why would you want to, anyway?
从理论上讲,您可以想出一个对象系统来强制执行自己的严格类型,但它不会执行,而且……无论如何,您为什么要这样做?
If you need strict typing, use a strictly typed language.
如果您需要严格的类型,请使用严格类型的语言。

