为什么 PHP 中需要类型提示?

2024-03-20

我无法理解 PHP 中类型提示的重要性。

显然 PHP 中的“类型提示”可以定义如下:

“类型提示”强制您仅传递特定类型的对象。 这可以防止您传递不兼容的值,并创建一个 如果您与团队合作等,则为标准。

那么,在最基本的级别上进行类型提示,不需要让代码真正工作吗?

我有以下代码来尝试理解发生了什么......

索引.php

<?php
include 'Song.php';

$song_object = new Song;

$song_object->title = "Beat it!";
$song_object->lyrics = "It doesn't matter who's wrong or right... just beat it!";


function sing(Song $song)
{
    echo "Singing the song called " . $song->title;
    echo "<p>" . $song->lyrics . "</p>";
}

sing($song_object);

Song.php

<?php

class Song
{
    public $title;
    public $lyrics;
}

代码在函数 sing() 中带或不带小类型提示的情况下执行其操作;

因此,这让我相信类型提示只是一种编码约定,以确保仅使用某些类并且不需要生成功能代码,这是正确的吗?

正如上面的引用所暗示的,类型提示是为了如果您与团队合作,请制定标准.

我在这里错过了什么吗?


类型提示不是必需的,但它可以让您发现某些类型的错误。例如,您可能有一个需要整数的函数或方法。 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 这样经常渴望在类型之间自动转换的语言特别有用。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 PHP 中需要类型提示? 的相关文章

随机推荐