在PHP中的对象类型提示

Sar*_* B. 7 php type-hinting

我需要帮助理解对象的类型提示.我尝试搜索stackoverflow但找不到任何其他用户解释其使用的东西.如果你找到一个让我知道.首先让我解释一下我的理解.

当使用类型提示数组时,用户必须输入一个数组参数,否则会引发错误.

<?php
function something(array $myval)
{
    return print_r($myval);
}
Run Code Online (Sandbox Code Playgroud)

当我用对象尝试它时,我得到一个错误.我可能写错了,但请帮助我理解如何写它.

<?php
class Person
{
    function name($name)
    {
        return $name;
    }
}

$foo = new Person();

function doSomething(Person $lname)
{
    return $lname->name;
}

doSomething('smith');
Run Code Online (Sandbox Code Playgroud)

根据我的理解,当一个函数类型提示对象Person(在这个例子中)时,参数变量将有权访问对象方法,就像实例化一个对象并回显其方法一样.我错了,但请纠正我.我的另一个问题是,如果在Person参数可以访问Person方法的情况下这是真的,那么这与仅仅实例化Person类并手动回显方法有什么不同.

Jea*_*aul 12

使用你的例子:

$foo = new Person;
$foo->name = 'smith';

$something = doSomething($foo);

echo $something;
Run Code Online (Sandbox Code Playgroud)

类型提示意味着您传递的任何内容都必须是您提示的类型(与其类型相同)的实例.

因此,如果您提示Person只接受该类型的对象.

在您给出的示例中,您尝试传递字符串而不是对象.

更新

"类型提示"强制您仅传递特定类型的对象.这可以防止您传递不兼容的值,并在您与团队等合作时创建标准.

所以,假设你有一个功能sing().您希望确保它只接受类型的对象Song.

让我们创建我们的课程Song:

class Song{

public $title;
public $lyrics;

}
Run Code Online (Sandbox Code Playgroud)

和我们的功能唱歌().我们将输入提示以Song确保不能将任何其他类型的参数传递给它:

function sing(Song $song){

echo "Singing the song called " .$song->title;
echo "<p>" . $song->lyrics . "</p>";

}
Run Code Online (Sandbox Code Playgroud)

现在,再次,该函数只能接受类型的对象,Song因为这是我们在声明(Song $song)中暗示的.

让我们创建一首歌并传递它:

$hit = new Song;

$hit->title = "Beat it!";
$hit->lyrics = "It doesn't matter who's wrong or right... just beat it!";
Run Code Online (Sandbox Code Playgroud)

然后我们打电话:

sing($hit);
Run Code Online (Sandbox Code Playgroud)

哪个会好起来的.

现在,假设我们有一个班级Poem:

class Poem{

public $title;
public $lyrics;

}

$poem = new Poem;

$poem->title = "Look at the sea";
$poem->lyrics = "How blue, blue like the sky, in which we fly..."
Run Code Online (Sandbox Code Playgroud)

如果我们尝试使用我们的函数'sing'来调用它;

sing($poem)
Run Code Online (Sandbox Code Playgroud)

我们将得到一个错误,因为$poem它不是我们在创建函数时暗示的对象类型sing().