これはすぐに意見の問題になる可能性がありますが、ゆるいタイピングはバグが発生する可能性を高めると感じています. 適切な場合もあるかもしれませんが、一般的に、信頼性と保守性が必要なコード (おそらく「柔軟」以上) では、厳密な型指定が安全です。
PHP 5 には「型ヒント」があります。
PHP 5.0 以降では、クラス名またはインターフェース名を型ヒントとして使用できます。または、次のようにしますself
。
<?php
function testFunction(User $user) {
// `$user` must be a User() object.
}
array
PHP 5.1 以降では、型ヒントとしても使用できます。
<?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 以降、これはType Declarationと呼ばれるようになりました。
PHP 7 ではReturn Type Declarationsも導入され、関数が返す型を指定できるようになりました。この関数は次を返す必要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 など)。