类型提示并非必须,但它可以帮助您捕获某些类型的错误。例如,您可能有一个需要整数的函数或方法。PHP会愉快地将“看起来像数字的字符串”转换为整数,这可能导致难以调试的行为。如果您在代码中指定了您需要一个整数,这可以防止这些类型的错误在第一时间发生。许多程序员认为以这种方式保护他们的代码是最佳实践。
作为这种操作的具体示例,让我们看一下您的index.php
文件的更新版本:
index.php
<?php
include 'Song.php';
include 'Test.php';
$song_object = new Song;
$test_object = new Test;
$song_object->title = "Beat it!";
$song_object->lyrics = "It doesn't matter who's wrong or right... just beat it!";
$test_object->title = "Test it!";
$test_object->lyrics = "It doesn't matter who's wrong or right... just test it!";
function sing(Song $song)
{
echo "Singing the song called " . $song->title;
echo "<p>" . $song->lyrics . "</p>";
}
sing($song_object);
sing($test_object);
除了新的Test.php
文件外,我还添加了:
Test.php
<?php
class Test
{
public $title;
public $lyrics;
}
当我现在运行
index.php
时,会出现以下错误:
输出:
Singing the song called Beat it!<p>It doesn't matter who's wrong or right...
just beat it!</p>PHP Catchable fatal error: Argument 1 passed to sing() must
be an instance of Song, instance of Test given, called in test/index.php on
line 22 and defined in test/index.php on line 15
Catchable fatal error: Argument 1 passed to sing() must be an instance of
Song, instance of Test given, called in test/index.php on line 22 and defined
in test/index.php on line 15
这是 PHP 提醒我在调用 "sing()" 函数时,使用了错误类型的类。这个提示很有用,即使上面的示例可以工作,但"Test"类可能与 "Song" 类不同。这可能会导致以后难以调试的错误。以这种方式使用提示,开发人员可以在它们引起问题之前防止类型错误。这在像 PHP 这样的语言中特别有用,该语言常常渴望自动转换数据类型。