This could quickly become a matter of opinion, but, I feel that loose typing introduces more possibilities for bugs to occur. There may be some cases where it's appropriate, but generally, for code that needs to be reliable and maintainable (possibly above "flexible"), strict typing is safer.
PHP 5 has "type hinting":
As of PHP 5.0, you can use class or interface names as a type hint, or self
:
<?php
function testFunction(User $user) {
// `$user` must be a User() object.
}
As of PHP 5.1, you can also use array
as a type hint:
<?php
function getSortedArray(array $array) {
// $user must be an array
}
PHP 5.4 adds callable
for functions/closures.
<?php
function openWithCallback(callable $callback) {
// $callback must be an callable/function
}
As of PHP 7.0, scalar types can be used as well (int
, string
, bool
, float
):
<?php
function addToLedger(string $item, int $quantity, bool $confirmed, float $price) {
...
}
As of PHP 7, this is now called a Type Declaration.
PHP 7 also introduces Return Type Declarations, allowing you to specify what type a function returns. This function must return a float
:
<?php
function sum($a, $b): float {
return $a + $b;
}
If you're not using PHP7, you can use the type hints that are available, and fill the remaining gaps with proper PHPDoc documentation:
<?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;
}
Many editors can parse these comments and warn you about improper typing (PHPStorm, for example).