Type hinting for classes and interfaces was added in 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);
The above script outputs:
Chris is being enrolled at University of Edinburgh
<?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);
The above example outputs the same as before:
Chris is being enrolled at University of Edinburgh
The self
keyword can be used as a type hint to indicate that the value must be an instance of the class that declares the method.