类型提示不是必需的,但它可以让您发现某些类型的错误。例如,您可能有一个需要整数的函数或方法。 PHP 将会愉快地转换 https://php.net/manual/en/language.types.type-juggling.php将“数字查找字符串”转换为整数,这可能会导致难以调试行为。如果您在代码中指定特别需要一个整数,这可以首先防止此类错误。许多程序员认为以这种方式保护他们的代码是最佳实践。
作为实际操作的具体示例,让我们看一下您的更新版本index.php
file:
索引.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
现在,我收到以下错误:
Output:
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 这样经常渴望在类型之间自动转换的语言特别有用。