PHP 类型提示类和接口
示例
在PHP5中添加了有关类和接口的类型提示。
类类型提示
<?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关键字可被用作一种类型的提示,以指示该值必须是一个声明所述方法的类的一个实例。