这可能很快成为一个意见问题,但是,我觉得松散的类型会引入更多发生错误的可能性。可能在某些情况下它是合适的,但通常,对于需要可靠和可维护的代码(可能高于“灵活”),严格类型更安全。
PHP 5 有“类型提示”:
从 PHP 5.0 开始,您可以使用类或接口名称作为类型提示,或者self
:
<?php
function testFunction(User $user) {
// `$user` must be a User() object.
}
从 PHP 5.1 开始,您还可以将array
其用作类型提示:
<?php
function getSortedArray(array $array) {
// $user must be an array
}
PHP 5.4 添加callable
了函数/闭包。
<?php
function openWithCallback(callable $callback) {
// $callback must be an callable/function
}
从 PHP 7.0 开始,也可以使用标量类型int
( , string
, bool
, float
):
<?php
function addToLedger(string $item, int $quantity, bool $confirmed, float $price) {
...
}
从 PHP 7 开始,这现在称为类型声明。
PHP 7 还引入了返回类型声明,允许您指定函数返回的类型。此函数必须返回一个float
:
<?php
function sum($a, $b): float {
return $a + $b;
}
如果您不使用 PHP7,则可以使用可用的类型提示,并使用适当的PHPDoc 文档填补剩余的空白:
<?php
/**
* Generates a random string of the specified length, composed of upper-
* and lower-case letters and numbers.
*
* @param int $length Number of characters to return.
* @return string Random string of $length characters.
*/
public function generateRandomString($length)
{
// ...
return $randomString;
}
许多编辑器可以解析这些注释并警告您输入不当(例如 PHPStorm)。