输入提示类和接口

在 PHP 5 中添加了类和接口的类型提示。

类类型提示

<?php

class Student
{
    public $name = 'Chris';
}

class School
{
    public $name = 'University of Edinburgh';
}

function enroll(Student $student, School $school)
{
    echo $student->name . ' is being enrolled at ' . $school->name;
}

$student = new Student();
$school = new School();

enroll($student, $school);

上面的脚本输出:

克里斯正在爱丁堡大学就读

接口类型提示

<?php

interface Enrollable {};
interface Attendable {};

class Chris implements Enrollable
{
    public $name = 'Chris';
}

class UniversityOfEdinburgh implements Attendable
{
    public $name = 'University of Edinburgh';
}

function enroll(Enrollable $enrollee, Attendable $premises)
{
    echo $enrollee->name . ' is being enrolled at ' . $premises->name;
}

$chris = new Chris();
$edinburgh = new UniversityOfEdinburgh();

enroll($chris, $edinburgh);

以上示例输出与以前相同:

克里斯正在爱丁堡大学就读

自我提示

self 关键字可用作类型提示,以指示该值必须是声明该方法的类的实例。