Type hinting classes and interfaces

suggest change

Type hinting for classes and interfaces was added in PHP 5.

Class type hint

<?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

Interface type hint

<?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

Self type hints

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Type hinting:
* Type hinting classes and interfaces

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
29 Type hinting
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR