类型提示不是必需的,但它可以让你发现某些类型的错误。例如,您可能有一个需要整数的函数或方法。PHP会很乐意将“数字字符串”转换为整数,这可能会导致难以调试的行为。如果在代码中指定特别需要一个整数,则可以首先防止此类 Bug。许多程序员认为以这种方式保护他们的代码是一种最佳实践。
作为实际操作的具体示例,让我们看一下文件的更新版本:index.php
索引.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
测试.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()
这很有用,因为即使上面的示例有效,该类也可能与类不同。这可能会导致以后难以调试的错误。以这种方式使用提示为开发人员提供了一种在类型错误导致问题之前防止它们的方法。这在像PHP这样的语言中特别有用,它通常渴望在类型之间自动转换。TestSong